<?php

function output($data){
    ajax_return($data);exit;
}
function getDealCateArray(){

}
function get_baseroot(){}

function get_abs_wap_url_root($content)
{
    return str_replace("/mapi/../public","/public",$content);

}

function get_abs_wap_avatar_url_root($content)
{
    return str_replace("/mapi/public","/public",$content);

}

function user_check($username_email,$pwd)
{
//	$pwd = addslashes($pwd);
    if($username_email&&$pwd)
    {
        //$sql = "select *,id as uid from ".DB_PREFIX."user where (user_name='".$username_email."' or email = '".$username_email."' or mobile = '".$username_email."') and is_delete = 0";
        //$sql = "select *,id as uid from ".DB_PREFIX."user where (user_name='".$username_email."' or money_encrypt = AES_ENCRYPT('".$username_email."','".AES_DECRYPT_KEY."') or mobile_encrypt = AES_ENCRYPT('".$username_email."','".AES_DECRYPT_KEY."')) and is_delete = 0";
        $sql = "select *,id as uid,AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name,AES_DECRYPT(email_encrypt,'".AES_DECRYPT_KEY."') as email,AES_DECRYPT(idno_encrypt,'".AES_DECRYPT_KEY."') as idno,AES_DECRYPT(money_encrypt,'".AES_DECRYPT_KEY."') as money,AES_DECRYPT(mobile_encrypt,'".AES_DECRYPT_KEY."') as mobile from ".DB_PREFIX."user where (user_name='".$username_email."' or money_encrypt = AES_ENCRYPT('".$username_email."','".AES_DECRYPT_KEY."') or mobile_encrypt = AES_ENCRYPT('".$username_email."','".AES_DECRYPT_KEY."')) and is_delete = 0";

        $user_info = $GLOBALS['db']->getRow($sql);

        $is_use_pass = false;
        if (strlen($pwd) != 32){
            if($user_info['user_pwd']==md5($pwd.$user_info['code']) || $user_info['user_pwd']==md5($pwd)){
                $is_use_pass = true;

            }
        }
        else{
            if($user_info['user_pwd']==$pwd){
                $is_use_pass = true;
            }
        }
        if($is_use_pass)
        {
            es_session::set("user_info",$user_info);
            $GLOBALS['user_info'] = $user_info;
            return $user_info;
        }
        else
            return null;
    }
    else
    {
        return null;
    }
}
function get_is_has_loans($is_has_loans,$deal){
    if($deal['deal_status'] >= 4 || $deal['deal_status'] == 2){
        if($is_has_loans==0){
            return '<a href="javascript:show_detail('.$deal['id'].')" style="color:red">否</a>';
        }
        else{
            return "<span style='color:red'>是</span>";
        }
    }
    else
    {
        return "否";
    }
}
function get_time_type(){

}
function a_get_deal_type($type,$id)
{
    $deal = M("Deal")->getById($id);
    if($deal['is_coupon'])
        return l("COUNT_TYPE_".$deal['deal_type']);
    else
        return l("NO_DEAL_COUPON_GEN");

}

function a_get_time_status($time_status,$deal_id)
{
    $str = l("TIME_STATUS_".$time_status);
    if($time_status == 2)
    {
        $str .= "<br />&nbsp;".M("Deal")->where("id=".$deal_id)->getField("reopen").l("REOPEN_SUBMIT");
    }
    return $str;
}

function a_get_buy_status($buy_status,$deal_id)
{


    $count = "&nbsp;&nbsp;[<a href='javascript:void(0);' onclick='show_detail(".$deal_id.")'; style='color:red;'>".l("COUNT_TOTAL_DEAL")."</a>]";


    return l("BUY_STATUS_".$buy_status).$link.$count;
}
function get_buy_type_title($buy_type)
{
    return l("DEAL_BUY_TYPE_".$buy_type);
}
function get_is_has_received($is_has_received,$deal){
    if($deal['deal_status']==3 || $deal['deal_status'] == 2  || ((($deal['start_time'] + $deal['end_date'] *24*3600 - 1) < TIME_UTC) && $deal['deal_status'] == 1) || $deal['deal_status'] == 1){
        if($is_has_received==0 && ($deal['deal_status'] == 2 || ((($deal['start_time'] + $deal['end_date'] *24*3600 - 1) < TIME_UTC) && $deal['deal_status'] == 1))){
            if($deal['deal_status'] == 1){
                if((($deal['start_time'] + $deal['end_date'] *24*3600 - 1) < TIME_UTC) && $deal['deal_status'] == 1)
                    return "未返还";
                else
                    return '<a href="javascript:show_detail('.$deal['id'].')" style="color:red">未满标</a>';
            }
            else
                return '<a href="javascript:show_detail('.$deal['id'].')" style="color:red">'.($deal['buy_count'] > 0 ? "未返还" : "未返还").'</a>';
        }
        else{
            if($deal['buy_count'] > 0){
                if($deal['is_has_received']==0){
                    return '<a href="javascript:show_detail('.$deal['id'].')" style="color:red">未返还</a>';
                }
                else{
                    return "<span style='color:red'>已返还</span>";
                }
            }
            else
                return "未返还";
        }
    }
    else{
        return "未返还";
    }
}

function get_ips_status($s,$deal){
    if(app_conf("OPEN_IPS") == 0){
        return "未开启功能";
    }
    $msg = "";
    if($deal['mer_bill_no'] == ""){
        if($deal['deal_status']>=3 || $deal['deal_status']==2 || $deal['buy_count'] >0){
            $msg .="无法同步<br>";
        }
        else{
            $msg .='<a href="http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterSubject&pOperationType=1&deal_id='.$deal['id'].'" target="_blank">同步</a><br>';
        }
    }
    else{
        $msg .="已同步<br>";
    }
    /*if($deal['mer_bill_no'] != "" && $deal['agency_id'] > 0){
        if($deal['ips_guarantor_bill_no'] == ""){
            if($deal['deal_status']>=3 || $deal['deal_status']==2 || $deal['buy_count'] >0){
                $msg .="&nbsp;无法同步[担]";
            }
            else{
                $msg .='&nbsp;<a href="http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterGuarantor&deal_id='.$deal['id'].'" target="_blank">同步[担]</a>';
            }
        }
        else{
            $msg .="&nbsp;已同步[担]<br>";
        }
    }*/

    if($deal['deal_status'] == 5  && $deal['ips_over'] == 0 && $deal['ips_bill_no'] != ""){
        $msg .='&nbsp;<a href="http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterSubject&pOperationType=2&status=1&deal_id='.$deal['id'].'" target="_blank">还款完成</a>';
    }

    return $msg;
}

function get_repay_plan2($id,$deal){
    $str = "";
    if($deal['deal_status']>=4)
        $str .= '<a href="javascript:repay_plan('.$id.');">还款计划</a>&nbsp;';

    if(((($deal['start_time'] + $deal['end_date'] *24*3600 - 1) > TIME_UTC) && $deal['deal_status'] == 1) || $deal['deal_status']==2 || ($deal['deal_status']==1 && $deal['buy_count'] > 0) || $deal['deal_status']>=4){
        $str .= '<a href="javascript:show_detail('.$id.');">投标详情和操作</a>&nbsp;';
    }

    return $str;
}

function check_del($id,$deal){
    if($deal['deal_status'] ==0)
        return '<a href="javascript:del('.$id.');">删除</a>&nbsp;';
}

/*拆标*/
function do_apart($id,$deal){
    if($deal['deal_status'] == 1 && $deal['load_money'] >0 && $deal['ips_bill_no'] ==""){
        return '<a href="javascript:do_apart('.$id.');">拆标</a>&nbsp;';
    }
}

function get_is_advance($tag,$id){
    if($tag)
    {
        return "<span class='is_advance' onclick='set_advance(".$id.",this);'>是</span>";
    }
    else
    {
        return "<span class='is_advance' onclick='set_advance(".$id.",this);'>否</span>";
    }
}
function get_is_hidden($is_hidden,$id)
{
    if($is_hidden)
    {
        return "<span class='is_advance' onclick='set_hidden(".$id.",this);'>是</span>";
    }
    else
    {
        return "<span class='is_advance' onclick='set_hidden(".$id.",this);'>否</span>";
    }
}
function get_adm_name($admin_id)
{
    $admin_info = M("admin")->getById($admin_id);
    return $admin_info["adm_name"];
}
function get_deal_contract($id)
{
    return "<a href='javascript:void(0);' onclick='open_contract(".$id.")'>合同</a>";
    //return "x";
}
function interestrate_send($id,$deal)
{
    if($deal["deal_status"] >= 4 && $deal["use_interestrate"] == 1)
    {
        return "<a href='javascript:void(0);' onclick='interestrate_send(".$id.")'>发放加息券红包</a>";
    }

}
function es_session_start($session_id){

    session_start();
}

//获取GMTime
function get_gmtime()
{
    return (time() - date('Z'));
}

function to_date($utc_time, $format = 'Y-m-d H:i:s') {
    if (empty ( $utc_time )) {
        return '';
    }
    $timezone = intval(8);
    if(is_array($utc_time)){
        $time = $utc_time[0] + $timezone * 3600;
    }else{
        $time = $utc_time + $timezone * 3600;
    }
    return date ($format, $time );
}

function to_timespan($str, $format = 'Y-m-d H:i:s')
{
    $timezone = intval(app_conf('TIME_ZONE'));
    //$timezone = 8;
    $time = intval(strtotime($str));
    if($time!=0)
        $time = $time - $timezone * 3600;

    $is_0 = intval($str);

    if($is_0==0)
        $time = 0;

    return $time;
}


function valid_tag($str)
{
    return preg_replace("/<(?!div|ol|ul|li|sup|sub|span|br|img|p|h1|h2|h3|h4|h5|h6|\/div|\/ol|\/ul|\/li|\/sup|\/sub|\/span|\/br|\/img|\/p|\/h1|\/h2|\/h3|\/h4|\/h5|\/h6|blockquote|\/blockquote|strike|\/strike|b|\/b|i|\/i|u|\/u)[^>]*>/i","",$str);
}

/**
 * 获取指定时间与当前时间的时间间隔
 *
 * @access  public
 * @param   integer      $time
 *
 * @return  string
 */
function getBeforeTimelag($time)
{
    if($time == 0)
        return "";

    static $today_time = NULL,
    $before_lang = NULL,
    $beforeday_lang = NULL,
    $today_lang = NULL,
    $yesterday_lang = NULL,
    $hours_lang = NULL,
    $minutes_lang = NULL,
    $months_lang = NULL,
    $date_lang = NULL,
    $sdate = 86400;

    if($today_time === NULL)
    {
        $today_time = TIME_UTC;
        $before_lang = '前';
        $beforeday_lang = '前天';
        $today_lang = '今天';
        $yesterday_lang = '昨天';
        $hours_lang = '小时';
        $minutes_lang = '分钟';
        $months_lang =  '月';
        $date_lang =  '日';
    }

    $now_day = to_timespan(to_date($today_time,"Y-m-d")); //今天零点时间
    $pub_day = to_timespan(to_date($time,"Y-m-d")); //发布期零点时间

    $timelag = $now_day - $pub_day;

    $year_time = to_date($time,'Y');
    $today_year = to_date($today_time,'Y');

    if($year_time < $today_year)
        return to_date($time,'Y:m:d H:i');

    $timelag_str = to_date($time,' H:i');

    $day_time = 0;
    if($timelag / $sdate >= 1)
    {
        $day_time = floor($timelag / $sdate);
        $timelag = $timelag % $sdate;
    }

    switch($day_time)
    {
        case '0':
            $timelag_str = $today_lang.$timelag_str;
            break;

        case '1':
            $timelag_str = $yesterday_lang.$timelag_str;
            break;

        case '2':
            $timelag_str = $beforeday_lang.$timelag_str;
            break;

        default:
            $timelag_str = to_date($time,'m'.$months_lang.'d'.$date_lang.' H:i');
            break;
    }
    return $timelag_str;
}


/**
 * 获取取时长
 * $begintime int型
 * $endtime
 */
function time_length($begintime,$endtime){
    if(!is_numeric($begintime)){
        $begintime = to_timespan($begintime);
    }
    if(!is_numeric($endtime)){
        $endtime = to_timespan($endtime);
    }

    $limit_time = $endtime -$begintime;
    $str = "";
    if($limit_time > 0){
        $day = intval($limit_time / 3600 / 24);
        if($day > 0){
            $str .= "<span>".$day."</span>天";
        }
        $hour  = intval(($limit_time % (3600 * 24)) / 3600);

        if($day > 0 ){
            $str .= "<span>".$hour."</span>时";
        }
        elseif($hour > 0){
            $str .= "<span>".$hour."</span>时";
        }

        $min = intval(($limit_time % 3600)/60) ;

        if($hour > 0 ){
            $str .= "<span>".$min."</span>分";
        }
        elseif($min > 0){
            $str .= "<span>".$min."</span>分";
        }


        $sec = $limit_time % 60 ;
        $str .= "<span>".$sec."</span>秒";

    }
    else{
        $str .= "<span>0</span>秒";
    }

    return $str;
}

//获取客户端IP
function get_client_ip2() {
    //使用wap时，是通过中转方式，所以要在wap/index.php获取客户ip,转入到:sjmapi上 chenfq by add 2014-12-17
    if (isset($GLOBALS['request']['client_ip']) && !empty($GLOBALS['request']['client_ip']))
        $ip = $GLOBALS['request']['client_ip'];
    else if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
        $ip = getenv ( "HTTP_CLIENT_IP" );
    else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
        $ip = getenv ( "HTTP_X_FORWARDED_FOR" );
    else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
        $ip = getenv ( "REMOTE_ADDR" );
    else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
        $ip = $_SERVER ['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return strim($ip);
}

//过滤注入
function filter_injection(&$request)
{
    $pattern = "/(select[\s])|(insert[\s])|(update[\s])|(delete[\s])|(from[\s])|(where[\s])/i";
    foreach($request as $k=>$v)
    {
        if(preg_match($pattern,$k,$match))
        {
            die("SQL Injection denied!");
        }

        if(is_array($v))
        {
            filter_injection($v);
        }
        else
        {

            if(preg_match($pattern,$v,$match))
            {
                die("SQL Injection denied!");
            }
        }
    }

}

//过滤请求
function filter_request(&$request)
{
    if(1)
    {
        foreach($request as $k=>$v)
        {
            if(is_array($v))
            {
                filter_request($request[$k]);
            }
            else
            {
                $request[$k] = stripslashes(trim($v));
            }
        }
    }

}

function adddeepslashes(&$request)
{

    foreach($request as $k=>$v)
    {
        if(is_array($v))
        {
            adddeepslashes($request[$k]);
        }
        else
        {
            $request[$k] = addslashes(trim($v));
        }
    }
}

//request转码
function convert_req(&$req)
{
    foreach($req as $k=>$v)
    {
        if(is_array($v))
        {
            convert_req($req[$k]);
        }
        else
        {
            if(!is_u8($v))
            {
                $req[$k] = iconv("gbk","utf-8",$v);
            }
        }
    }
}

function stripdeepslashes(&$request)
{

    if(is_array($request))
    {
        foreach($request as $k=>$v)
        {
            if(is_array($v))
            {
                stripdeepslashes($request[$k]);
            }
            else
            {
                $request[$k] = stripslashes(trim($v));
            }
        }
    }
    else
        $request = stripslashes($request);
}

function quotes($content)
{
    //if $content is an array
    if (is_array($content))
    {
        foreach ($content as $key=>$value)
        {
            //$content[$key] = mysql_real_escape_string($value);
            $content[$key] = addslashes($value);
        }
    } else
    {
        //if $content is not an array
        $content = addslashes($content);
        //mysql_real_escape_string($content);
    }
    return $content;
}

function strim($str)
{
    return quotes(htmlspecialchars(trim($str)));
}
function btrim($str)
{
    return quotes(trim($str));
}

function is_u8($string)
{
    return preg_match('%^(?:
		 [\x09\x0A\x0D\x20-\x7E]            # ASCII
	   | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
	   |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
	   | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
	   |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
	   |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
	   | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
	   |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
   )*$%xs', $string);
}

//清除缓存
function clear_cache()
{
    //系统后台缓存
    syn_dealing();
    clear_dir_file(get_real_path()."public/runtime/admin/Cache/");
    clear_dir_file(get_real_path()."public/runtime/admin/Data/_fields/");
    clear_dir_file(get_real_path()."public/runtime/admin/Temp/");
    clear_dir_file(get_real_path()."public/runtime/admin/Logs/");
    @unlink(get_real_path()."public/runtime/admin/~app.php");
    @unlink(get_real_path()."public/runtime/admin/~runtime.php");
    @unlink(get_real_path()."public/runtime/admin/lang.js");
    @unlink(get_real_path()."public/runtime/app/config_cache.php");


    //数据缓存
    clear_dir_file(get_real_path()."public/runtime/app/data_caches/");
    clear_dir_file(get_real_path()."public/runtime/app/db_caches/");
    $GLOBALS['cache']->clear();
    clear_dir_file(get_real_path()."public/runtime/data/");

    //模板页面缓存
    clear_dir_file(get_real_path()."public/runtime/app/tpl_caches/");
    clear_dir_file(get_real_path()."public/runtime/app/tpl_compiled/");
    @unlink(get_real_path()."public/runtime/app/lang.js");

    //脚本缓存
    clear_dir_file(get_real_path()."public/runtime/statics/");

    clear_dir_file(get_real_path()."public/runtime/wap/");
    clear_dir_file(get_real_path()."public/runtime/wap/statics/");
    clear_dir_file(get_real_path()."public/runtime/wap/tpl_caches/");
    clear_dir_file(get_real_path()."public/runtime/wap/tpl_compiled/");
}
function clear_dir_file($path)
{
    if ( $dir = opendir( $path ) )
    {
        while ( $file = readdir( $dir ) )
        {
            $check = is_dir( $path. $file );
            if ( !$check )
            {
                @unlink( $path . $file );
            }
            else
            {
                if($file!='.'&&$file!='..')
                {
                    clear_dir_file($path.$file."/");
                }
            }
        }
        closedir( $dir );
        rmdir($path);
        return true;
    }
}

//同步未过期团购的状态
function syn_dealing()
{
    $deals = $GLOBALS['db']->getAll("select id from ".DB_PREFIX."deal where is_effect = 1 and deal_status not in (3,5) and is_delete = 0 AND load_money/borrow_amount <= 1 LIMIT 10 ");
    foreach($deals as $v)
    {
        syn_deal_status($v['id']);
    }
}

function check_install()
{

}

//同步XXID的团购商品的状态,time_status,buy_status
function syn_deal_status($id)
{
    $deals_time = TIME_UTC;
    $deal_info = $GLOBALS['db']->getRow("select *,(start_time + enddate*24*3600 - ".$deals_time.") as remain_time,(load_money/borrow_amount*100) as progress_point from ".DB_PREFIX."deal where id = ".$id);

    if($deal_info['deal_status'] == 5 || $deal_info['is_effect'] == 0){
        return $deal_info;
    }

    if($deal_info['deal_status']!=3){
        if($deal_info['progress_point'] <100){
            $data['load_money'] = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load  WHERE deal_id=$id ");
            $data['progress_point'] = $deal_info['progress_point'] = round($data['load_money']/$deal_info['borrow_amount']*100,2);
        }

        if(($deal_info['progress_point'] >=100 || $data['progress_point'] >=100) && floatval($deal_info['load_money']) >=floatval($deal_info['borrow_amount'])){

            if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_inrepay_repay WHERE deal_id=$id") >0){
                $data['deal_status'] = 5;
                $repay_info =  $GLOBALS['db']->getRow("SELECT sum(true_repay_money) As all_repay_money  FROM ".DB_PREFIX."deal_load_repay WHERE has_repay = 1 AND deal_id=$id");
                if($repay_info){
                    $data['repay_money'] = $repay_info['all_repay_money'];
                }
                $data['last_repay_time'] = $GLOBALS['db']->getOne("SELECT true_repay_time FROM ".DB_PREFIX."deal_inrepay_repay WHERE deal_id=$id");
            }
            //判断是否是借款状态还是已还款完毕
            elseif(($deal_info['deal_status']==4&&$deal_info['repay_start_time']>0) || ($deal_info['deal_status']==2 && $deal_info['repay_start_time']>0 && $deal_info['repay_start_time'] <= $deals_time)){
                $repay_info =  $GLOBALS['db']->getRow("SELECT sum(true_repay_money) As all_repay_money  FROM ".DB_PREFIX."deal_load_repay WHERE has_repay=1 AND deal_id=$id");
                if(!empty($repay_info['all_repay_money'])){
                    $data['repay_money'] = $repay_info['all_repay_money'];

                    if($deal_info['repay_time_type'] == 0){
                        $data['next_repay_time'] = $deal_info['repay_start_time'] + $deal_info['repay_time']*24*3600;
                    }
                    else{
                        $last_repay_time = $GLOBALS['db']->getOne("SELECT MAX(repay_time)  FROM ".DB_PREFIX."deal_repay WHERE has_repay=1 AND deal_id=$id");;
                        $data['last_repay_time'] =  $last_repay_time;
                        if((int)$last_repay_time)
                            $data['next_repay_time'] = next_replay_month($last_repay_time);
                        else
                            $data['next_repay_time'] = next_replay_month($deal_info['repay_start_time']);
                    }

                }
                elseif($deal_info['deal_status']==4){
                    if($deal_info['repay_time_type'] == 0){
                        $data['next_repay_time'] = $deal_info['repay_start_time'] + $deal_info['repay_time']*24*3600;
                    }
                    else{
                        if(is_last_repay($deal_info['loantype'])==1){
                            $data['next_repay_time'] = next_replay_month($deal_info['repay_start_time'],$deal_info['repay_time']);
                        }
                        elseif(is_last_repay($deal_info['loantype'])==2){
                            $data['next_repay_time'] = next_replay_month($deal_info['repay_start_time'],3);

                        }
                        else
                            $data['next_repay_time'] = next_replay_month($deal_info['repay_start_time']);
                    }
                }

                //判断是否完成还款
                if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE has_repay<>1 AND deal_id=$id ") == 0){
                    $data['deal_status'] = 5;
                }
                else{
                    $data['deal_status'] = 4;
                }
            }
            else{
                //获取最后一次的投标记录
                if($deal_info['success_time'] == 0){
                    $data['success_time'] = $deal_info['success_time'] = $GLOBALS['db']->getOne("SELECT max(create_time) FROM ".DB_PREFIX."deal_load WHERE deal_id=$id ");
                }

                $data['deal_status'] = 2;
            }
        }
        elseif($deal_info['remain_time'] <= 0 && $deal_info['deal_status']==1){
            //投标时间超出 更新为流标
            $data['deal_status'] = 1;
            //$data['bad_time'] = $deal_info['start_time'] + $deal_info['enddate']*24*3600;
            $data['bad_time'] = TIME_UTC;
            $data['bad_date'] = to_date(TIME_UTC,"Y-m-d");
        }
        /*elseif($deal_info['remain_time'] > 0 && $deal_info['deal_status']==0){
			$data['deal_status'] = 1;
		}*/
    }

    //投标人数
    $sdata = $GLOBALS['db']->getRow("SELECT count(*) as buy_count,sum(money) as load_money FROM ".DB_PREFIX."deal_load WHERE deal_id=$id");
    $data['buy_count'] = $sdata['buy_count'];
    $data['load_money'] = floatval($sdata['load_money']);

    //流标 移入后台手动操作
    /*if($deal_info['deal_status'] ==3 || $data['deal_status']==3){
		//流标时返还
		require_once APP_ROOT_PATH."system/libs/user.php";
		$r_load_list = $GLOBALS['db']->getAll("SELECT id,user_id,money FROM ".DB_PREFIX."deal_load WHERE is_repay=0 AND deal_id=$id");
		foreach($r_load_list as $k=>$v){
			modify_account(array("money"=>$v['money']),$v['user_id'],"标:".$deal_info['id'].",流标返还");
			$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_repay=1 WHERE id=".$v['id']);
		}
		//发送流标通知
		if($deal_info['is_send_bad_msg']==0){
			$data['is_send_bad_msg'] = 1;
			//发邮件
			send_deal_faild_mail_sms($id,$deal_info,$deal_info['user_id']);
			//站内信
			send_deal_faild_site_sms($id,$deal_info,$deal_info['user_id']);

			//添加到动态
			insert_topic("deal_bad",$id,$deal_info['user_id'],get_user_name($deal_info['user_id'],false),0);
		}
	}*/

    //发送流标通知
    if(($deal_info['deal_status'] ==3 || $data['deal_status']==3) && $deal_info['is_send_bad_msg']==0){
        $data['is_send_bad_msg'] = 1;
        //发邮件和短信
        send_deal_faild_mail_sms($id,$deal_info,$deal_info['user_id']);
        //站内信
        send_deal_faild_site_sms($id,$deal_info,$deal_info['user_id']);

        //添加到动态
        insert_topic("deal_bad",$id,$deal_info['user_id'],get_user_name($deal_info['user_id'],false),0);
    }

    //放款给用户 移入后台手动操作
    /*if($deal_info['is_has_loans']==0 && $data['deal_status']==4){
		$data['is_has_loans'] = 1;
		require_once APP_ROOT_PATH."system/libs/user.php";
		modify_account(array("money"=>$deal_info['borrow_amount']),$deal_info['user_id'],"标:".$deal_info['id'].",招标成功");
		//扣除服务费
		$services_fee = $deal_info['borrow_amount']*floatval(trim($deal_info['services_fee']))/100;
		modify_account(array("money"=>-$services_fee),$deal_info['user_id'],"服务费");


		//发借款成功邮件
		send_deal_success_mail_sms($id,$deal_info);
		//发借款成功站内信
		send_deal_success_site_sms($id,$deal_info);

		//返利给用户
		if(floatval(app_conf("USER_BID_REBATE"))!=0){
			$load_list = $GLOBALS['db']->getAll("SELECT id,user_id,`money` FROM ".DB_PREFIX."deal_load where deal_id=".$id." and is_rebate = 0 ");
			foreach($load_list as $lk=>$lv){
				$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_rebate =1 WHERE id=".$lv['id']." AND is_rebate = 0 AND user_id=".$lv['user_id']);
				if($GLOBALS['db']->affected_rows()){
					modify_account(array("money"=>$lv['money']*floatval(app_conf("USER_BID_REBATE"))/100),$lv['user_id'],"标:".$id.",返利");
				}
			}
		}
	}*/

    if($deal_info['is_effect']==0 && $data['deal_status']==5){
        unset($data['deal_status']);
    }

    $GLOBALS['db']->autoExecute(DB_PREFIX."deal",$data,"UPDATE","id=".$id);

    //自动投标功能
    //2013-8-15 排除了   借贷者在外 and usa.user_id <>'".$deal_info['user_id']."'
    if(app_conf("OPEN_AUTOBID") == 1 && $deal_info['ips_bill_no'] =="" && $deal_info['remain_time'] > 0 && $deal_info['start_time'] < TIME_UTC){
        if($deal_info['is_new'] == 0 && ($deal_info['deal_status'] == 1 || $data['deal_status']==1) && $deal_info['remain_time'] >0 && $deals_time - $deal_info['start_time'] >=1800 && $deal_info['progress_point'] <=95){
            $sql = "SELECT u.id,u.user_name,usa.fixed_amount,d.uloadtype,d.min_loan_money FROM ".DB_PREFIX."user_autobid usa " .
                "LEFT JOIN ".DB_PREFIX."user u ON u.id=usa.user_id  " .
                "LEFT JOIN ".DB_PREFIX."deal d ON d.id=".$deal_info['id']." ".
                "LEFT JOIN ".DB_PREFIX."user du ON du.id = d.user_id ".
                "WHERE (usa.fixed_amount >=d.min_loan_money or d.min_loan_money = 0) AND (usa.fixed_amount <= d.max_loan_money or d.max_loan_money = 0) " .
                "AND usa.fixed_amount <= d.borrow_amount*0.2 AND usa.is_effect = 1 ".
                "AND (d.rate between usa.min_rate AND usa.max_rate) " ;

            if($deal_info['repay_time_type'] == 0){
                $sql .="AND usa.bind_day = 1 ";
            }
            else{
                $sql .="AND (d.repay_time between usa.min_period AND usa.max_period) " ;
            }

            $sql .= "AND usa.user_id not in (SELECT user_id FROM ".DB_PREFIX."deal_load WHERE deal_id=$id) and usa.user_id <>d.user_id " .
                "AND (du.level_id between usa.min_level AND usa.max_level) " .
                "AND usa.fixed_amount < (d.borrow_amount - d.load_money) ".
                "AND AES_DECRYPT(u.money_encrypt,'".AES_DECRYPT_KEY."')-usa.retain_amount >= usa.fixed_amount ".
                "AND FIND_IN_SET(d.cate_id,usa.deal_cates) ".
                "GROUP BY usa.user_id ORDER BY usa.last_bid_time ASC";


            $autobid_user = $GLOBALS['db']->getRow($sql);
            //开始投标
            if($autobid_user && $deal_info['borrow_amount'] > $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_info['id']) + $autobid_user['fixed_amount'])
            {
                $biddata['deal_id'] = $id;
                $biddata['money'] = $autobid_user['uloadtype'] == 1 ? $autobid_user['min_loan_money'] : $autobid_user['fixed_amount'];
                $biddata['is_auto'] = 1;
                $insertbiddata = return_deal_load_data($biddata,$autobid_user,$deal_info);

                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal SET load_money=load_money+".$insertbiddata['money']." WHERE load_money+".$insertbiddata['money']."<= borrow_amount AND id=".$id);

                $load_id = 0;
                if($GLOBALS['db']->affected_rows() > 0){
                    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$insertbiddata,"INSERT");
                    $load_id = $GLOBALS['db']->insert_id();
                }
                if($load_id > 0){
                    if($GLOBALS['db']->getOne("SELECT COUNT(*) FROM ".DB_PREFIX."deal_load WHERE user_id = ".$autobid_user['id']." and deal_id=".$id." AND id < ".$load_id) > 0){
                        $GLOBALS['db']->query("DELETE FROM ".DB_PREFIX."deal_load where id=".$load_id);
                    }
                    else{
                        $msg = '[<a href="'.url("index","deal",array("id"=>$deal_info['id'])).'" target="_blank">'.$deal_info['name'].'</a>]的投标,付款单号'.$load_id;
                        require_once APP_ROOT_PATH."system/libs/user.php";
                        modify_account(array("money"=>-$autobid_user['fixed_amount'],'lock_money'=>$autobid_user['fixed_amount']),$autobid_user['id'],$msg,2);
                        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."user_autobid SET last_bid_time=".TIME_UTC." WHERE user_id=".$autobid_user['id']);
                    }

                }
            }
        }
    }

    return $data;
}


function LoadLoanModule($loantype){
    static $make_module = array();
    if(!isset($make_module[$loantype])){
        require APP_ROOT_PATH."system/loantype/loantype_".$loantype.".class.php";
        $obj_class = "loantype_".$loantype;
        $make_module[$loantype] = new $obj_class;
    }
    return $make_module[$loantype];
}

/**
 * 生成还款计划和回款计划
 */
function make_repay_plan($deal){
    $loantype = intval($deal['loantype']);
    $LoanModule = LoadLoanModule($loantype);
    $list = $LoanModule->make_repay_plan($deal);
    $total_money = array();
    foreach($list as $i=>$load_repay){
        if($old_info = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." AND repay_time=".$load_repay['repay_time']."  ") ){
            $repay_id = $old_info['id'];
            if($old_info['has_repay']==0){
                $load_repay['l_key'] = $i;
                $load_repay['status'] = 0;

                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$load_repay,"UPDATE","deal_id=".$deal['id']." AND repay_time=".$load_repay['repay_time']."");
            }
            else{
                unset($load_repay['self_money']);
                unset($load_repay['repay_money']);
                unset($load_repay['has_repay']);
                unset($load_repay['manage_money']);
                unset($load_repay['manage_money_rebate']);
                $GLOBALS['db']->query("UPDATE FROM ".DB_PREFIX."deal_repay SET l_key='".$i."' WHERE deal_id=".$deal['id']." AND repay_time=".$load_repay['repay_day']."");
            }

        }
        else{

            $load_repay['l_key'] = $i;
            $load_repay['status'] = 0;
            $load_repay['has_repay'] = 0;

            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$load_repay,"INSERT");
            $repay_id = $GLOBALS['db']->insert_id();
        }

        make_user_repay_plan($deal,$i,$load_repay['repay_time'],$old_info['true_repay_time'],$repay_id,$total_money);
    }
}

/**
 * 生成投标者的回款计划
 */
function make_user_repay_plan($deal,$idx,$repay_day,$true_time,$repay_id,&$total_money){
    static $fload_users;
    if(!isset($fload_users[$deal['id']])){
        $fload_users[$deal['id']] = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."deal_load  WHERE deal_id=".$deal['id']." ORDER BY id ASC ");
    }

    $loantype = intval($deal['loantype']);
    $LoanModule = LoadLoanModule($loantype);

    $load_users = $LoanModule->make_user_repay_plan($deal,$idx,$repay_day,$true_time,$repay_id,$fload_users[$deal['id']],$total_money);

    foreach($load_users as $kk=>$vv){
        $repay_data =array();
        $repay_data = $vv;

        if($old_info = $GLOBALS['db']->getRow("SELECT id,has_repay,interestrate_money,load_id FROM ".DB_PREFIX."deal_load_repay WHERE deal_id=".$vv['deal_id']." AND u_key=$kk and l_key= $idx ")){
            if($old_info['has_repay']==1)
            {
                unset($repay_data['self_money']);
                unset($repay_data['repay_money']);
                unset($repay_data['interest_money']);
                unset($repay_data['manage_money']);
                unset($repay_data['repay_manage_money']);
                unset($repay_data['manage_interest_money']);
                unset($repay_data['manage_interest_money_rebate']);
                unset($repay_data['has_repay']);
            }
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$repay_data,"UPDATE","id=".$old_info['id']);
            /*//更新deal_load interestrate_money
			$load_data = array();
			$load_date["interestrate_money"] = $old_info["interestrate_money"];
			$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$load_data,"UPDATE","id=".$old_info['load_id']);	*/
        }
        else{
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$repay_data,"INSERT");

            /*//更新deal_load interestrate_money
			$load_data = array();
			$load_data["interestrate_money"] = $repay_data["interestrate_money"];

			$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$load_data,"UPDATE","id=".$repay_data['load_id']);*/
        }
    }


    $all_money = $GLOBALS['db']->getOne("SELECT sum(repay_money) FROM ".DB_PREFIX."deal_load_repay WHERE deal_id=".$vv['deal_id']." AND l_key= $idx ");
    if($all_money != 0)
        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_repay SET repay_money = $all_money WHERE deal_id=".$vv['deal_id']." AND l_key= $idx");

}

/**
 * 每月还款
 */
function deal_repay_money($deal){
    $loantype = intval($deal['loantype']);
    $LoanModule = LoadLoanModule($loantype);
    return $LoanModule->deal_repay_money($deal);
}

/**
 * 提前还款
 */
function inrepay_repay($loaninfo,$k,$time_utc = 0){
    $loantype = intval($loaninfo['deal']['loantype']);
    $LoanModule = LoadLoanModule($loantype);

    return $LoanModule->inrepay_repay($loaninfo,$k,$time_utc);
}

/**
 * 判断是否最后一起才还款
 */
function is_last_repay($loantype){
    $loantype = intval($loantype);
    $LoanModule = LoadLoanModule($loantype);
    return $LoanModule->is_last_repay();
}

/**
 * 债券转让计算 天标不支持
 * $transfer array  必要参数  load_money[投标金额] how_much_month[剩余期数] rate[费率]
 */
function deal_transfer($transfer){

    $loantype = intval($transfer['loantype']);
    $LoanModule = LoadLoanModule($loantype);
    return $LoanModule->transfer($transfer);
}

/**
 * 获取借款方式名称
 */
function loantypename($loantype,$type=1){
    static $loantype_info = array();
    $loantype = (int)$loantype;
    if(!isset($loantype_info[$loantype])){
        $read_modules = true;
        $loantype_info[$loantype] = require(APP_ROOT_PATH."system/loantype/loantype_".$loantype.".class.php");
    }
    if($type==1)
        return $loantype_info[$loantype]['sub_name'];
    else
        return $loantype_info[$loantype]['name'];

}


/**
 * 更新债权转让状态
 */
function syn_transfer_status($id=0,$deal_id=0){
    $ids = array();
    $extw = "";
    if($id > 0){
        $extw .= " AND dlt.id = ".intval($id);
    }

    if($deal_id > 0){
        $extw.= " AND d.id = ".intval($deal_id);
    }

    $tids = $GLOBALS['db']->getAll("SELECT dlt.id,dlt.load_id,dlt.create_time,dlt.user_id,dlt.t_user_id from ".DB_PREFIX."deal_load_transfer dlt LEFT join ".DB_PREFIX."deal d on d.id=dlt.deal_id WHERE dlt.status=1 and dlt.t_user_id=0 and (dlt.near_repay_time  < ".next_replay_month(to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d"),-1)." or d.deal_status = 5) ".$extw);
    if(app_conf('MAIL_ON')==1)
        $tmpl_mail = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_TRANSFER_FAILED'",false);
    if(app_conf('SMS_ON')==1)
        $tmpl_sms = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_TRANSFER_FAILED'",false);
    foreach($tids as $k=>$v)
    {
        $ids[] = $v['id'];

        //发送消息
        $msg_conf = get_user_msg_conf($v['user_id']);
        //if($msg_conf['sms_transferfail']==1 || $msg_conf['mail_transferfail']==1){
        $v['tuser'] = get_user("*",$v['t_user_id']);
        $v['user'] = get_user("*",$v['user_id']);
        //}

        if($msg_conf['sms_transferfail']==1){

            $notice['shop_title']=app_conf("SHOP_TITLE");
            $notice['url']="“<a href=\"".url("index","transfer#detail",array("id"=>$v['id']))."\">Z-".$v['load_id']."</a>”";
            $notice['msg'] = "借款人还款,或借款人逾期还款";
            $notice['op_auth'] ="自动";
            $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SYN_TRANSFER_REVOKE'",false);
            $GLOBALS['tmpl']->assign("notice",$notice);
            $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);
            send_user_msg("",$content,0,$v['user_id'],TIME_UTC,0,true,17);
        }
        //邮件
        if($msg_conf['mail_transferfail']==1 && app_conf('MAIL_ON')==1){
            $tmpl_content = $tmpl_mail['content'];

            $notice['user_name'] = $v['user']['user_name'];
            $notice['transfer_time'] = to_date($v['create_time'],"Y年m月d日");
            $notice['transfer_id'] = "Z-".$v['load_id'];
            $notice['bad_msg'] = "借款人还款,或借款人逾期还款";
            $notice['deal_url'] = SITE_DOMAIN.url("index","transfer#detail",array("id"=>$v['id']));
            $notice['site_name'] = app_conf("SHOP_TITLE");
            $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
            $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
            $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");



            $GLOBALS['tmpl']->assign("notice",$notice);

            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
            $msg_data['dest'] = $v['user']['email'];
            $msg_data['send_type'] = 1;
            $msg_data['title'] = "债权：“Z-".$v['load_id']."”撤销通知";
            $msg_data['content'] = addslashes($msg);
            $msg_data['send_time'] = 0;
            $msg_data['is_send'] = 0;
            $msg_data['create_time'] = TIME_UTC;
            $msg_data['user_id'] = $v['user_id'];
            $msg_data['is_html'] = $tmpl_mail['is_html'];
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        }
        //短信
        if(app_conf('SMS_ON')==1){
            $tmpl_content = $tmpl_sms['content'];

            $notice['user_name'] = $v['user']['user_name'];
            $notice['transfer_time'] = to_date($v['create_time'],"Y年m月d日");
            $notice['transfer_id'] = "Z-".$v['load_id'];
            $notice['site_name'] = app_conf("SHOP_TITLE");
            $notice['bad_msg'] = "借款人还款,或借款人逾期还款";


            $GLOBALS['tmpl']->assign("notice",$notice);

            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
            $msg_data['dest'] = $v['user']['mobile'];
            $msg_data['send_type'] = 0;
            $msg_data['title'] = "债权：“Z-".$v['load_id']."”撤销通知";
            $msg_data['content'] = addslashes($msg);
            $msg_data['send_time'] = 0;
            $msg_data['is_send'] = 0;
            $msg_data['create_time'] = TIME_UTC;
            $msg_data['user_id'] = $v['user_id'];
            $msg_data['is_html'] = $tmpl_sms['is_html'];
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        }
    }
    if(count($ids) > 0)
        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load_transfer SET status=0 WHERE t_user_id=0 and id in (".implode(",",$ids).") ");
}

//更新用户统计
function sys_user_status($user_id,$is_cache = false,$make_cache=false){
    if($user_id == 0)
        return ;
    $data = false;
    if($make_cache == false){
        if($is_cache == true){
            $key = md5("USER_STATICS_".$user_id);
            $data = load_dynamic_cache($key);
        }
    }
    if($data==false){
        //留言数
        $data['dp_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."message use index(idx_0)  WHERE user_id=$user_id AND is_effect = 1");
        //总借款额
        $data['borrow_amount'] = $GLOBALS['db']->getOne("SELECT sum(borrow_amount) FROM ".DB_PREFIX."deal  use index(idx_0) WHERE deal_status in(4,5) AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1 ");

        $has_repay_rs = $GLOBALS['db']->getRow("SELECT sum(true_repay_money) as total_repay_money,sum(true_manage_money) as total_manage_money FROM ".DB_PREFIX."deal_repay WHERE user_id=$user_id");
        //已还本息
        $data['repay_amount'] = $has_repay_rs['total_repay_money'];

        //已还管理费
        $data['repay_manage_amount'] = $has_repay_rs['total_manage_money'];

        //投资返利
        $data['rebate_money'] = $GLOBALS['db']->getOne("SELECT sum(rebate_money) FROM ".DB_PREFIX."deal_load WHERE is_has_loans=1 AND user_id=$user_id");

        //发布借款笔数
        $data['deal_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal use index(idx_1) WHERE user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1 ");
        //成功借款笔数
        $data['success_deal_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal use index(idx_0) WHERE deal_status in (4,5) AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1 ");
        //还清笔数
        $data['repay_deal_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal use index(idx_0) WHERE deal_status = 5 AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1 ");
        //未还清笔数
        $data['wh_repay_deal_count'] = $data['success_deal_count'] - $data['repay_deal_count'];
        //提前还清笔数
        $data['tq_repay_deal_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_inrepay_repay WHERE user_id=$user_id");
        //正常还清笔数
        $data['zc_repay_deal_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal WHERE deal_status = 5 AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1  AND id not in (SELECT deal_id FROM ".DB_PREFIX."deal_inrepay_repay WHERE user_id=$user_id)");
        //加权平均借款利率
        //$data['avg_rate'] = $GLOBALS['db']->getOne("SELECT sum(rate)/count(*) FROM ".DB_PREFIX."deal use index(idx_0) WHERE deal_status in (4,5) AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1  ");
        $avg_rate = $GLOBALS['db']->getRow("SELECT sum(rate) as sum_rate ,count(*) as sum_count FROM ".DB_PREFIX."deal use index(idx_0) WHERE deal_status in(4,5) AND user_id=$user_id AND publish_wait = 0 and is_delete = 0 and is_effect=1  ");

        //加权平均借款利率【加债权】
        $repay_avg_rate = $GLOBALS['db']->getRow("SELECT sum(d.rate) as sum_rate ,count(*) as sum_count FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d ON d.id=dlr.deal_id WHERE (dlr.user_id = ".$user_id." and dlr.t_user_id = 0) or dlr.t_user_id = ".$user_id);

        $data["avg_rate"] =(floatval($avg_rate["sum_rate"])+floatval($repay_avg_rate["sum_rate"]))/(floatval($avg_rate["sum_count"])+floatval($repay_avg_rate["sum_count"]));

        //平均每笔借款金额
        $data['avg_borrow_amount'] = $data['borrow_amount'] / $data['success_deal_count'];

        //逾期本息
        $data['yuqi_amount'] = $GLOBALS['db']->getOne("SELECT (sum(repay_money) + sum(impose_money)) as new_amount FROM ".DB_PREFIX."deal_repay WHERE user_id=$user_id AND ((has_repay=1 and status in(2,3)) or (has_repay=0 AND (".TIME_UTC."- repay_time -24*3600 + 1 ) > 0) )");
        //逾期费用
        $data['yuqi_impose'] = $GLOBALS['db']->getOne("SELECT sum(repay_money) FROM ".DB_PREFIX."deal_repay WHERE has_repay=1 AND user_id=$user_id AND ((has_repay=1 and status in(2,3)) or (has_repay=0 AND (".TIME_UTC."- repay_time -24*3600 + 1 ) > 0))");

        //逾期次数
        $data['yuqi_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE user_id=".$user_id."  AND ((has_repay=1 AND status = 2) or (has_repay=0  AND (".TIME_UTC."- repay_time -24*3600 + 1 )/24/3600 between 1 and ".(intval(app_conf('YZ_IMPSE_DAY')) - 1)." ))");
        //严重逾期次数
        $data['yz_yuqi_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE user_id=$user_id AND ((has_repay=1 AND status = 3) or (has_repay=0  AND (".TIME_UTC."- repay_time -24*3600 + 1 )/24/3600 >= ".intval(app_conf('YZ_IMPSE_DAY')) ." ))");

        $load_info = $GLOBALS['db']->getRow("SELECT sum(true_interest_money - true_manage_money - true_manage_interest_money) as load_earnings,sum(true_repay_money - true_manage_money - true_manage_interest_money) AS load_repay_money,sum(true_reward_money) as load_reward_money FROM ".DB_PREFIX."deal_load_repay  WHERE  ((user_id = ".$user_id." and t_user_id = 0) or t_user_id = ".$user_id.") AND has_repay=1 ");
        //已赚利息
        $data['load_earnings'] = $load_info['load_earnings'];
        //已回收本息
        $data['load_repay_money'] = $load_info['load_repay_money'];
        //奖励收益
        $data['reward_money'] = $load_info['load_reward_money'];

        //坏账
        $data['bad_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay  WHERE user_id=".$user_id."  AND is_site_bad = 1 ");


        $need_load_info = $GLOBALS['db']->getRow("SELECT sum(repay_money) AS load_repay_money,sum(manage_money - true_manage_money) as total_manage_money FROM ".DB_PREFIX."deal_repay  WHERE has_repay=0 AND user_id=$user_id ");
        //待还本息【债权】
        //$t_need_load_info = $GLOBALS['db']->getRow("SELECT sum(repay_money) AS load_repay_money,sum(repay_manage_money) as total_manage_money FROM ".DB_PREFIX."deal_load_repay WHERE has_repay=0 AND t_user_id=$user_id");
        //print_r($t_need_load_info);die;
        //待还本息
        //$data['need_repay_amount'] = $need_load_info['load_repay_money'] + $t_need_load_info['load_repay_money'];
        $data['need_repay_amount'] = $need_load_info['load_repay_money'];
        //待还管理费
        //$data['need_manage_amount'] = $need_load_info['total_manage_money'] + $t_need_load_info['total_manage_money'];
        $data['need_manage_amount'] = $need_load_info['total_manage_money'];



        //邀请返利
        $data['referrals_money'] = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."referrals WHERE rel_user_id=".$user_id."  AND pay_time >0  ");

        //提现手续费
        $data['carry_fee_money'] = $GLOBALS['db']->getOne("SELECT sum(fee) FROM ".DB_PREFIX."user_carry WHERE user_id=".$user_id."  AND status =1  ");

        //充值手续费
        $data['incharge_fee_money'] = $GLOBALS['db']->getOne("SELECT sum(fee_amount) FROM ".DB_PREFIX."payment_notice WHERE user_id=".$user_id."  AND is_paid =1  ");

        //充值总额
        $data['incharge_money'] = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."payment_notice WHERE user_id=".$user_id." AND `is_paid`=1");
        //提现总额
        $data['carry_money'] = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."user_carry WHERE user_id=".$user_id." AND `status`=1");

        //投资统计管理费
        $data['load_manage_money'] = $GLOBALS['db']->getOne("SELECT sum(true_manage_money) FROM ".DB_PREFIX."deal_load_repay WHERE user_id=".$user_id." AND `has_repay`=1");

        //已赚提前还款违约金
        $data['load_tq_impose'] = $GLOBALS['db']->getOne("SELECT sum(impose_money) FROM ".DB_PREFIX."deal_load_repay WHERE has_repay=1 AND status = 0 AND ((user_id = ".$user_id." and t_user_id = 0) or t_user_id = ".$user_id.")");
        //已赚逾期罚息
        $data['load_yq_impose'] = $GLOBALS['db']->getOne("SELECT sum(impose_money) FROM ".DB_PREFIX."deal_load_repay WHERE has_repay=1 AND status in (2,3) AND ((user_id = ".$user_id." and t_user_id = 0) or t_user_id = ".$user_id.")");

        //借出加权平均收益率
        //$data['load_avg_rate'] = $GLOBALS['db']->getOne("SELECT sum(rate)/count(*) FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON d.id=dl.deal_id WHERE d.deal_status in(4,5) AND dl.user_id=$user_id");


        $load_avg_rate = $GLOBALS['db']->getRow("SELECT sum(rate) as sum_rate ,count(*) as sum_count FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON d.id=dl.deal_id WHERE d.deal_status in(4,5) AND dl.user_id=$user_id ");
        //借出加权平均收益率【加入债权】
        $load_repay_avg_rate = $GLOBALS['db']->getRow("SELECT sum(d.rate) as sum_rate ,count(*) as sum_count FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d ON d.id=dlr.deal_id WHERE (dlr.user_id = ".$user_id." and dlr.t_user_id = 0) or dlr.t_user_id = ".$user_id);
        //print_r($load_repay_avg_rate);die;
        if((floatval($load_avg_rate["sum_count"])+floatval($load_repay_avg_rate["sum_count"])) != 0)
            $data["load_avg_rate"] =(floatval($load_avg_rate["sum_rate"])+floatval($load_repay_avg_rate["sum_rate"]))/(floatval($load_avg_rate["sum_count"])+floatval($load_repay_avg_rate["sum_count"]));
        else
            $data["load_avg_rate"] = 0;
        /**/
        //托管待收总额
        $ips_money = $GLOBALS['db']->getRow("SELECT sum(dlr.repay_money) as ips_need_money FROM ".DB_PREFIX."deal_load_repay dlr left join ".DB_PREFIX."deal d on dlr.deal_id = d.id WHERE dlr.user_id=".$user_id." and dlr.has_repay= 0 and d.ips_bill_no <> '' ");

        $data["ips_need_money"] = round($ips_money["ips_need_money"],2);

        //托管待还总额
        $data["ips_repay_money"] = $GLOBALS['db']->getOne("SELECT sum(dl.repay_money) FROM ".DB_PREFIX."deal_repay dl left join ".DB_PREFIX."deal d on dl.deal_id = d.id WHERE dl.user_id=".$user_id." and dl.has_repay= 0 and d.ips_bill_no <> '' ");;

        //托管回款资金
        $data["ips_load_money"] = $GLOBALS['db']->getOne("SELECT sum(dlr.repay_money) as ips_need_money FROM ".DB_PREFIX."deal_load_repay dlr left join ".DB_PREFIX."deal d on dlr.deal_id = d.id WHERE dlr.user_id=".$user_id." and dlr.has_repay= 1 and d.ips_bill_no <> '' ");
        //托管充值资金
        $data['ips_incharge_money'] = round(get_ips_incharge($user_id),2);

        //托管的返利
        $data['ips_referrals_money'] = $GLOBALS['db']->getOne("SELECT sum(r.money) FROM ".DB_PREFIX."referrals r left join ".DB_PREFIX."deal d on r.deal_id = d.id  WHERE r.rel_user_id=".$user_id."  AND r.pay_time >0  and  d.ips_bill_no <> '' ");
        //$data["ips_incharge_money"] = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."payment_notice WHERE user_id=".$user_id." AND `is_paid`=1 and ");

        //总借出笔数
        $u_load = $GLOBALS['db']->getRow("SELECT count(*) as load_count,sum(money) as load_money FROM ".DB_PREFIX."deal_load WHERE user_id=$user_id and is_repay= 0 ");

        $data['load_count'] = $u_load['load_count'];
        //总借出金额
        $data['load_money'] = $u_load['load_money'];

        //总债权笔数【含债权转入】
        $t_u_load = $GLOBALS['db']->getRow("SELECT count(*) as load_count,sum(dlr.repay_money) as load_money  FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d ON d.id=dlr.deal_id LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id=dlr.load_id WHERE d.is_delete=0 AND d.is_effect=1 and dl.is_repay= 0 and  dlr.t_user_id = ".$user_id);

        $data['load_count'] = $data['load_count'] + $t_u_load['load_count'];

        //总借出金额【含债权转入】
        $data['load_money'] = floatval($data['load_money']) + floatval($t_u_load['load_money']);
        //已回收笔数
        $data['reback_load_count'] = $GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON d.id=dl.deal_id WHERE d.deal_status =5 AND dl.user_id=$user_id and d.is_delete = 0 and d.is_effect=1");

        //已回收笔数【含债权转入】
        $data['t_reback_load_count'] = $GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d ON d.id=dlr.deal_id WHERE d.deal_status =5 AND d.is_delete = 0 and d.is_effect=1 and  dlr.t_user_id = ".$user_id." ");

        //总已回收笔数
        $data['reback_load_count'] = $data['reback_load_count'] + $data['t_reback_load_count'];

        //待回收笔数【含债权转入】
        $data['wait_reback_load_count'] = $GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON d.id=dl.deal_id WHERE d.deal_status =4 AND dl.user_id=$user_id and d.is_delete = 0 and d.is_effect=1");

        $load_wait = $GLOBALS['db']->getRow("SELECT sum(self_money) as total_self_money,sum(self_money+interest_money) as total_repay_money,sum(manage_money + manage_interest_money) as load_wait_manage,sum(interest_money) as load_wait_earnings FROM ".DB_PREFIX."deal_load_repay where ((user_id = ".$user_id." and t_user_id = 0) or t_user_id = ".$user_id.") and has_repay = 0  ");

        //待回收本金
        $data['load_wait_self_money'] = $load_wait['total_self_money'];
        //待回收本息
        $data['load_wait_repay_money'] = $load_wait['total_repay_money'];
        //待回收利息
        $data['load_wait_earnings'] = $load_wait['load_wait_earnings'];
        //待回支出管理费
        $data['load_wait_manage'] = $load_wait['load_wait_manage'];




        if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user_sta WHERE user_id=".$user_id) > 0)
            $GLOBALS['db']->autoExecute(DB_PREFIX."user_sta",$data,"UPDATE","user_id=".$user_id);
        else{
            $data['user_id'] = $user_id;
            $GLOBALS['db']->autoExecute(DB_PREFIX."user_sta",$data,"INSERT");
        }

        if($data['deal_count'] > 0 || $data['load_count']){
            if($data['deal_count'] > 0)
                $u_data['is_borrow_in'] = 1;
            if($data['load_count'] > 0)
                $u_data['is_borrow_out'] = 1;
            $GLOBALS['db']->autoExecute(DB_PREFIX."user",$u_data,"UPDATE","id=".$user_id);
        }
        if(isset($key) && ($is_cache == true || $make_cache == true) ){
            set_dynamic_cache($key,$data);
        }
    }
    return $data;
}


//发送流标通知邮件
function send_deal_faild_mail_sms($deal_id,$deal_info=false,$user_id){
    if(!$deal_info && $deal_id ==0)
        return false;

    if(app_conf('MAIL_ON')==0 || app_conf('SMS_ON')==0)
        return false;

    if(!$deal_info)
        $deal_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);


    if(intval($deal_info['is_send_bad_msg'])==1)
        return false;

    $msg_conf = get_user_msg_conf($user_id);

    //借入者的邮件通知
    if(($msg_conf['mail_myfail'] == 1 || !$msg_conf) && app_conf('MAIL_ON')==1){
        $user_info = get_user_info("*","id = ".$deal_info['user_id']);
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_DEAL_FAILED'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $user_info['user_name'];
        $notice['deal_name'] = $deal_info['name'];
        $notice['deal_publish_time'] = to_date($deal_info['create_time'],"Y年m月d日");
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
        $notice['send_deal_url'] = SITE_DOMAIN.url("index","borrow");
        $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
        $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
        $notice['bad_msg'] = $deal_info['bad_msg'];

        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $user_info['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "您的借款“".$deal_info['name']."”已流标！";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }
    //借入者的短信通知
    if(app_conf('SMS_ON')==1){
        if(!$user_info)
            $user_info = get_user_info("*","id = ".$deal_info['user_id']);
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_DEAL_FAILED'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $user_info['user_name'];
        $notice['deal_name'] = $deal_info['name'];
        $notice['deal_publish_time'] = to_date($deal_info['create_time'],"Y年m月d日");
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['bad_msg'] = $deal_info['bad_msg'];

        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $user_info['mobile'];
        $msg_data['send_type'] = 0;
        $msg_data['title'] = $user_info['user_name']."的借款“".$deal_info['name']."”流标通知";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }



    //获取投标列表
    $load_user_list = $GLOBALS['db']->getAll("SELECT user_name,user_id,create_time,money FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_info['id']);
    if($load_user_list){
        $load_mail_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_LOAD_FAILED'",false);
        $load_sms_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_LOAD_FAILED'",false);
        foreach($load_user_list as $k=>$v){
            $user_info = get_user_info("*","id = ".$v['user_id']);
            $load_msg_conf = get_user_msg_conf($v['user_id']);
            //邮件通知
            if($load_msg_conf['mail_myfail'] == 1 && app_conf('MAIL_ON')==1){
                $tmpl_content = $load_mail_tmpl['content'];
                $notice['user_name'] = $v['user_name'];
                $notice['deal_name'] = $deal_info['name'];
                $notice['money'] = number_format($v['money']);
                $notice['deal_url'] = SITE_DOMAIN.$deal_info['url'];
                $notice['deal_load_time'] = to_date($v['create_time'],"Y年m月d日");
                $notice['site_name'] = app_conf("SHOP_TITLE");
                $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
                $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
                $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
                $notice['bad_msg'] = $deal_info['bad_msg'];

                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = "您的所投的借款“".$deal_info['name']."”已流标！";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] =  $v['user_id'];
                $msg_data['is_html'] = $load_mail_tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
            //短信通知
            if(app_conf('SMS_ON')==1){
                $tmpl_content = $load_sms_tmpl['content'];
                $notice['user_name'] = $v['user_name'];
                $notice['deal_name'] = $deal_info['name'];
                $notice['money'] = number_format($v['money']);
                $notice['deal_load_time'] = to_date($v['create_time'],"Y年m月d日");
                $notice['site_name'] = app_conf("SHOP_TITLE");
                $notice['bad_msg'] = $deal_info['bad_msg'];

                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['mobile'];
                $msg_data['send_type'] = 0;
                $msg_data['title'] = $v['user_name']."的投标“".$deal_info['name']."”流标通知";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] =  $v['user_id'];
                $msg_data['is_html'] = $load_sms_tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }
    }
}

//发送满标通知邮件
function send_deal_success_mail_sms($deal_id,$deal_info=false){
    if(!$deal_info && $deal_id ==0)
        return false;

    if(app_conf('MAIL_ON')==0 && app_conf('SMS_ON')==0)
        return false;


    if(!$deal_info)
        $deal_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);


    if(intval($deal_info['is_send_success_msg'])==1)
        return false;


    //借入者的邮件通知
    if(app_conf('MAIL_ON')==1){
        $user_info = get_user_info("*","id = ".$deal_info['user_id']);
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_DEAL_SUCCESS'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $user_info['user_name'];
        $notice['deal_name'] = $deal_info['name'];
        $notice['deal_publish_time'] = to_date($deal_info['create_time'],"Y年m月d日");
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
        $notice['send_deal_url'] = SITE_DOMAIN.url("index","borrow");
        $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
        $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
        $notice['bad_msg'] = $deal_info['bad_msg'];

        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $user_info['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "您的借款“".$deal_info['name']."”已满标！";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }
    //借入者的短信通知
    if(app_conf('SMS_ON')==1 && app_conf('SMS_DEAL_SUCCESS')==1){
        if(!$user_info)
            $user_info = get_user_info("*","id = ".$deal_info['user_id']);
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_DEAL_SUCCESS'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $user_info['user_name'];
        $notice['deal_name'] = $deal_info['name'];
        $notice['deal_publish_time'] = to_date($deal_info['create_time'],"Y年m月d日");
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['bad_msg'] = $deal_info['bad_msg'];

        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $user_info['mobile'];
        $msg_data['send_type'] = 0;
        $msg_data['title'] = $user_info['user_name']."的借款“".$deal_info['name']."”满标通知";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }


    //获取投标列表
    $load_user_list = $GLOBALS['db']->getAll("SELECT user_name,user_id,create_time,money FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_info['id']);
    if($load_user_list){
        $load_mail_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_LOAD_SUCCESS'",false);
        $load_sms_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_LOAD_SUCCESS'",false);
        foreach($load_user_list as $k=>$v){
            $user_info = get_user_info("*","id = ".$v['user_id']);
            $load_msg_conf = get_user_msg_conf($v['user_id']);
            if($load_msg_conf['mail_bidsuccess'] == 1 && app_conf('MAIL_ON')==1){
                $tmpl_content = $load_mail_tmpl['content'];
                $notice['user_name'] = $v['user_name'];
                $notice['deal_name'] = $deal_info['name'];
                $notice['deal_url'] = SITE_DOMAIN.$deal_info['url'];
                $notice['deal_load_time'] = to_date($v['create_time'],"Y年m月d日");
                $notice['money'] = format_price($v["money"]);
                $notice['site_name'] = app_conf("SHOP_TITLE");
                $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
                $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
                $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");

                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = "您的所投的借款“".$deal_info['name']."”已满标！";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] =  $v['user_id'];
                $msg_data['is_html'] = $load_mail_tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }

            //短信通知
            if(app_conf('SMS_ON')==1){
                $tmpl_content = $load_sms_tmpl['content'];
                $notice['user_name'] = $v['user_name'];
                $notice['deal_name'] = $deal_info['name'];
                $notice['deal_load_time'] = to_date($v['create_time'],"Y年m月d日");
                $notice['money'] = format_price($v["money"]);
                $notice['site_name'] = app_conf("SHOP_TITLE");

                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['mobile'];
                $msg_data['send_type'] = 0;
                $msg_data['title'] = $v['user_name']."的投标“".$deal_info['name']."”满标通知";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] =  $v['user_id'];
                $msg_data['is_html'] = $load_sms_tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }
    }
}

//发送流标站内信
function send_deal_faild_site_sms($deal_id,$deal_info=false,$user_id){
    if(!$deal_info && $deal_id ==0)
        return false;

    if(!$deal_info)
        $deal_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);


    if(intval($deal_info['is_send_bad_msg'])==1)
        return false;

    $msg_conf = get_user_msg_conf($user_id);

    if($msg_conf['sms_myfail'] == 1){

        $notice['shop_title'] = app_conf("SHOP_TITLE");
        $notice['time'] = to_date($deal_info['create_time'],"Y年m月d日");
        $notice['deal_name'] = "<a href=\"".url("index","deal",array("id"=>$deal_info['id']))."\">".$deal_info['name']."</a>";
        $notice['bad_msg'] = $deal_info['bad_msg'];
        $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_FAILD_SITE_SMS'",false);
        $GLOBALS['tmpl']->assign("notice",$notice);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);
        send_user_msg("",$content,0,$user_id,TIME_UTC,0,true,10);
    }

    //获取投标列表
    $load_user_list = $GLOBALS['db']->getAll("SELECT user_name,user_id,create_time FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_info['id']);
    if($load_user_list){
        foreach($load_user_list as $k=>$v){
            $load_msg_conf = get_user_msg_conf($v['user_id']);
            if($load_msg_conf['sms_myfail'] == 1 || !$load_msg_conf){

                $notice['site_title']=app_conf("SHOP_TITLE");
                $notice['time']=to_date($v['create_time'],"Y年m月d日");
                $notice['deal_name']="<a href=\"".url("index","deal",array("id"=>$deal_info['id']))."\">".$deal_info['name']."</a>";
                $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_FAILD_SITE_SMS'",false);
                $GLOBALS['tmpl']->assign("notice",$notice);
                $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);
                send_user_msg("",$content,0,$user_id,TIME_UTC,0,true,10);

            }
        }
    }
}

//发送满标站内信
function send_deal_success_site_sms($deal_id,$deal_info=false){
    if(!$deal_info && $deal_id ==0)
        return false;

    if(!$deal_info)
        $deal_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);


    if(intval($deal_info['is_send_success_msg'])==1)
        return false;

    //获取投标列表
    $load_user_list = $GLOBALS['db']->getAll("SELECT user_name,user_id,create_time FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_info['id']);
    if($load_user_list){
        foreach($load_user_list as $k=>$v){
            $load_msg_conf = get_user_msg_conf($v['user_id']);
            if($load_msg_conf['sms_bidsuccess'] == 1 || !$load_msg_conf){

                $notice['shop_title']=app_conf("SHOP_TITLE");
                $notice['time']=to_date($v['create_time'],"Y年m月d日");
                $notice['deal_name']="“<a href=\"".url("index","deal",array("id"=>$deal_info['id']))."\">".$deal_info['name']."</a>”";

                $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_SUCCESS_SITE_SMS'",false);
                $GLOBALS['tmpl']->assign("notice",$notice);
                $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);
                send_user_msg("",$content,0,$v['user_id'],TIME_UTC,0,true,16);
            }
        }
    }
}

//发送电子协议邮件
function send_deal_contract_email($deal_id,$deal,$user_id){

    if($deal_id ==0 && !$deal)
        return false;

    if(app_conf('MAIL_ON')==0 || app_conf('MAIL_SEND_CONTRACT_ON')==0)
        return false;

    if(!$deal)
        $deal = get_deal($deal_id);

    if(intval($deal['is_send_contract'])==1 || $deal['deal_status'] <> 4)
        return false;


    $GLOBALS['tmpl']->assign('deal',$deal);

    $loan_list = $GLOBALS['db']->getAll("select * FROM ".DB_PREFIX."deal_load WHERE deal_id='".$deal['id']."' ORDER BY create_time ASC");
    foreach($loan_list as $k=>$v){
        $vv_deal = array();
        $vv_deal['borrow_amount'] = $v['money'];
        $vv_deal['rate'] = $deal['rate'];
        $vv_deal['repay_time'] = $deal['repay_time'];
        $vv_deal['loantype'] = $deal['loantype'];
        $vv_deal['repay_time_type'] = $deal['repay_time_type'];

        $deal_rs =  deal_repay_money($vv_deal);
        $loan_list[$k]['get_repay_money'] = $deal_rs['month_repay_money'];
        if(is_last_repay($deal['loantype'])==1)
            $loan_list[$k]['get_repay_money'] = $deal_rs['remain_repay_money'];

        $user_info = get_user_info("*","id=".$v['user_id']);
        $loan_list[$k]['real_name'] = $user_info['real_name'];
    }

    $GLOBALS['tmpl']->assign('loan_list',$loan_list);

    if($deal['user']['sealpassed'] == 1){
        $credit_file = get_user_credit_file($deal['user_id']);
        $GLOBALS['tmpl']->assign('user_seal_url',$credit_file['credit_seal']['file_list'][0]);
    }

    $GLOBALS['tmpl']->assign('SITE_URL',str_replace(array("https://","http://"),"",SITE_DOMAIN));
    $GLOBALS['tmpl']->assign('SITE_TITLE',app_conf("SITE_TITLE"));
    $GLOBALS['tmpl']->assign('CURRENCY_UNIT',app_conf("CURRENCY_UNIT"));

    $msg = $GLOBALS['tmpl']->fetch("str:".get_contract($deal['contract_id']));

    $msg = "<div style=\"font-size:12px\"><div style=\"background-color: #FFFFFF; border:#dfe6ea solid 1px; padding: 5px 12px;\">" .$msg;
    $msg .= "<div style=\"position:relative; width:100%;  z-index:1; text-align:right; \" >
    	<img src=\"".get_domain()."/".APP_ROOT.app_conf("THIRD_STAMPER_IMG")."\" width=\"160\" height=\"160\"/>
    </div>";
    $msg .= "</div></div>";

    $msg_data  = array();
    $msg_data['dest'] = $deal['user']['email'];
    $msg_data['send_type'] = 1;
    $msg_data['title'] = "借款“".$deal['name']."”的电子协议！";
    $msg_data['content'] = addslashes($msg);
    $msg_data['send_time'] = 0;
    $msg_data['is_send'] = 0;
    $msg_data['create_time'] = TIME_UTC;
    $msg_data['user_id'] =  $deal['user_id'];
    $msg_data['is_html'] = 1;
    //插入数据库
    if($GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data)){
        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal set is_send_contract =1 where id =".$deal['id']);
    }

    //获取投资者的邮件
    $load_user_list = $GLOBALS['db']->getAll("SELECT u.user_name,AES_DECRYPT(u.email_encrypt,'".AES_DECRYPT_KEY."') as email,u.id FROM ".DB_PREFIX."user u LEFT JOIN  ".DB_PREFIX."deal_load dl ON u.id=dl.user_id WHERE dl.deal_id=".$deal['id']." GROUP BY u.id ");
    foreach($load_user_list as $k=>$v){
        $msg_data  = array();
        $msg_data['dest'] = $v['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "借款“".$deal['name']."”的电子协议！";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] =  $v['id'];
        $msg_data['is_html'] = 1;
        //插入数据库
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data);
    }
}

//发送投标回款短信
function send_repay_reback_sms_mail($deal_info,$loan_user_info,$unext_loan,$user_load_data,$all_shouyi_money,$all_impose_money){

    if(app_conf("SMS_ON")==1&&app_conf('SMS_REPAY_TOUSER_ON')==1 && $loan_user_info['mobile']!=""){

        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_SMS'");
        $tmpl_content = $tmpl['content'];
        $notice =array();
        $notice['user_name'] = $loan_user_info['user_name'];
        $notice['deal_name'] = $deal_info['sub_name'];
        $notice['deal_url'] = $deal_info['url'];
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['repay_money'] = number_format(($user_load_data['true_repay_money']+$user_load_data['impose_money']),2);
        if($unext_loan){
            $notice['need_next_repay'] = $unext_loan;
            $notice['next_repay_time'] = to_date($unext_loan['repay_day'],"Y年m月d日");
            $notice['next_repay_money'] = number_format($unext_loan['month_repay_money'],2);
        }
        else{
            $notice['all_repay_money'] = $all_shouyi_money;
            $notice['impose_money'] = $all_impose_money;
        }

        $GLOBALS['tmpl']->assign("notice",$notice);
        $sms_content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);

        $msg_data['dest'] = $loan_user_info['mobile'];
        $msg_data['send_type'] = 0;
        $msg_data['title'] = $msg_data['content'] = addslashes($sms_content);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $loan_user_info['id'];
        $msg_data['is_html'] = 0;
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }

    //回款通知
    if(app_conf("WEIXIN_MSG")==1){
        $user_info = get_user_info("*","id = ".$loan_user_info['id']);
        if($user_info['wx_openid']!='')
        {
            $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM207940989' ");
            $repay_money = number_format(($user_load_data['true_repay_money']+$user_load_data['impose_money']),2);
            $weixin_data['first'] = array('value'=>'投标回款短信通知','color'=>'#173177');
            $weixin_data['keyword1']=array('value'=>$deal_info['sub_name'],'color'=>'#173177');
            $weixin_data['keyword2']=array('value'=>$loan_user_info['user_name'],'color'=>'#173177');
            $weixin_data['keyword3']=array('value'=>$repay_money,'color'=>'#173177');
            weixin_tmpl_send($tmpl['template_id'],$loan_user_info['id'],$weixin_data);
        }
    }

    $msg_conf = get_user_msg_conf($loan_user_info['id']);

    //邮件
    if($msg_conf['mail_bidrepaid']==1 && app_conf('MAIL_ON')==1 && $loan_user_info['email']!=""){

        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_EMAIL'",false);
        $tmpl_content = $tmpl['content'];
        $notice =array();
        $notice['user_name'] = $loan_user_info['user_name'];
        $notice['deal_name'] = $deal_info['sub_name'];
        $notice['deal_url'] = $deal_info['url'];
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
        $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
        $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
        $notice['repay_money'] = number_format(($user_load_data['true_repay_money']+$user_load_data['impose_money']),2);
        if($unext_loan){
            $notice['need_next_repay'] = $unext_loan;
            $notice['next_repay_time'] = to_date($unext_loan['repay_day'],"Y年m月d日");
            $notice['next_repay_money'] = number_format($unext_loan['month_repay_money'],2);
        }
        else{
            $notice['all_repay_money'] = $all_shouyi_money;
            $notice['impose_money'] = $all_impose_money;
        }

        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $loan_user_info['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "“".$deal_info['name']."”回款通知";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $loan_user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        unset($notice);
    }

    //站内信
    if($msg_conf['sms_bidrepaid']==1){
        $notices =array();
        $notices['has_next_loan'] = 0;
        if($unext_loan){
            $notices['has_next_loan'] = 1;
            $notices['next_repay_time'] = to_date($unext_loan['repay_day'],"Y年m月d日");
            $notices['next_repay_money'] = number_format($unext_loan['month_repay_money'],2);
        }
        else{
            $notices['all_shouyi_money'] = $all_shouyi_money;
            $notices['all_impose_money'] = $all_impose_money;
        }
        $notices['site_title'] = app_conf("SHOP_TITLE");
        $notices['url'] = "“<a href=\"".$deal_info['url']."\">".$deal_info['name']."</a>”";
        $notices['repay_money'] = ($user_load_data['true_repay_money']+$user_load_data['impose_money']);

        $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SITE_REPAY'",false);
        $GLOBALS['tmpl']->assign("notice",$notices);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);

        send_user_msg("",$content,0,$loan_user_info['id'],TIME_UTC,0,true,9);
        unset($notices);
    }
}

function send_transfer_contract_email($id,$transfer=array()){
    if($id ==0 && !$transfer)
        return false;

    if(app_conf('MAIL_ON')==0 || app_conf('MAIL_SEND_CONTRACT_ON')==0)
        return false;

    if(!$transfer){
        $condition = ' AND dlt.id='.$id.' AND d.deal_status >= 4 and d.is_effect=1 and d.is_delete=0 and d.repay_time_type =1 and  d.publish_wait=0 and (dlt.user_id='.$GLOBALS['user_info']['id'].' or dlt.t_user_id = '.$GLOBALS['user_info']['id'].') ';
        $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id ";
        /*
		$sql = 'SELECT dlt.id,dlt.deal_id,dlt.load_id,dlt.transfer_amount,dlt.near_repay_time,dlt.user_id,d.next_repay_time,d.last_repay_time,d.rate,d.repay_start_time,d.repay_time,dlt.load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time,dlt.transfer_time,d.user_id as duser_id,d.tcontract_id FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

		$transfer = $GLOBALS['db']->getRow($sql);*/
        require_once APP_ROOT_PATH."/app/Lib/deal_func.php";
        $transfer = get_transfer($union_sql,$condition);
    }

    if($transfer){
        /*
		//下个还款日
		$transfer['next_repay_time_format'] = to_date($transfer['near_repay_time'],"Y 年 m 月 d 日");
		$transfer['near_repay_time_format'] = to_date(next_replay_month($transfer['near_repay_time']," -1 "),"Y 年 m 月 d 日");

		//什么时候开始借
		$transfer['repay_start_time_format']  = to_date($transfer['repay_start_time'],"Y 年 m 月 d 日");

		//还款日
		$transfer['final_repay_time'] = next_replay_month($transfer['repay_start_time'],$transfer['repay_time']);
		$transfer['final_repay_time_format'] = to_date($transfer['final_repay_time'],"Y 年 m 月 d 日");

		//剩余期数
		$transfer['how_much_month'] = how_much_month($transfer['near_repay_time'],$transfer['final_repay_time']) +1;

		$transfer_rs = deal_transfer($transfer);
		//本息还款金额
		$transfer['month_repay_money'] = $transfer_rs['month_repay_money'];
		//剩余多少钱未回
		$transfer['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
		//剩余多少本金未回
		$transfer['left_benjin'] = $transfer_rs['left_benjin'];


		$transfer['month_repay_money_format'] = format_price($transfer['month_repay_money']);

		$transfer['all_must_repay_money_format'] = format_price($transfer['all_must_repay_money']);

		$transfer['left_benjin_format'] = format_price($transfer['left_benjin']);
		//剩多少利息
		$transfer['left_lixi'] = $transfer['all_must_repay_money'] - $transfer['left_benjin'];
		$transfer['left_lixi_format'] = format_price($transfer['left_lixi']);

		//投标价格
		$transfer['load_money_format'] =  format_price($transfer['load_money']);

		//转让价格
		$transfer['transfer_amount_format'] =  format_price($transfer['transfer_amount']);

		//转让管理费
		$transfer['transfer_fee_format'] = format_price($transfer['transfer_amount']*(float)app_conf("USER_LOAD_TRANSFER_FEE"));

		//转让收益
		$transfer['transfer_income_format'] =  format_price($transfer['all_must_repay_money']-$transfer['transfer_amount']);

		if($transfer['tras_create_time'] !=""){
			$transfer['tras_create_time_format'] =  to_date($transfer['tras_create_time'],"Y 年 m 月 d 日");
		}

		$transfer['transfer_time_format'] =  to_date($transfer['transfer_time'],"Y 年 m 月 d 日");

		$transfer['user'] = get_user("user_name,email,real_name,idno,level_id",$transfer['user_id']);
		$transfer['tuser'] = get_user("user_name,email,real_name,idno,level_id",$transfer['t_user_id']);
		$transfer['duser'] = get_user("user_name,email,real_name,idno,level_id",$transfer['duser_id']);
		 */
        $GLOBALS['tmpl']->assign('transfer',$transfer);


        $GLOBALS['tmpl']->assign('SITE_URL',str_replace(array("https://","http://"),"",SITE_DOMAIN));
        $GLOBALS['tmpl']->assign('SITE_TITLE',app_conf("SITE_TITLE"));
        $GLOBALS['tmpl']->assign('CURRENCY_UNIT',app_conf("CURRENCY_UNIT"));

        $contract = $GLOBALS['tmpl']->fetch("str:".get_contract($transfer['tcontract_id']));

        $contract = "<div style=\"font-size:12px\"><div style=\"background-color: #FFFFFF; border:#dfe6ea solid 1px; padding: 5px 12px;\">" .$contract;
        $contract .= "<div style=\"position:relative; width:100%;  z-index:1; text-align:right; \" >
    	<img src=\"".get_domain()."/".APP_ROOT.app_conf("THIRD_STAMPER_IMG")."\" width=\"160\" height=\"160\"/>
    </div>";
        $contract .= "</div></div>";

        $msg_data['dest'] = $transfer['user']['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "债权“Z-".$transfer['load_id']."”的电子协议！";
        $msg_data['content'] = addslashes($contract);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] =  $transfer['user_id'];
        $msg_data['is_html'] = 1;
        //发送给转让者
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data);
        //发送给承接者
        $msg_data['dest'] = $transfer['tuser']['email'];
        $msg_data['user_id'] =  $transfer['t_user_id'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data);

    }
}

function get_contract($id){
    static $contract_array =array();
    if(!isset($contract_array[$id])){
        $contract = load_auto_cache("contract_cache");
        $contract_array[$id] = $contract[$id]['content'];
    }
    return $contract_array[$id];
}


//发注册验证邮件
function send_user_verify_mail($email,$code,$user_info=array(),$immediately=true)
{
    $re = array('msg_id'=>0, 'status'=>0,'msg'=>'');

    if(app_conf("MAIL_ON")==1)
    {
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_USER_VERIFY'");
        $tmpl_content = $tmpl['content'];
        $verify['email'] = $email;
        $verify['code'] = $code;
        $GLOBALS['tmpl']->assign("verify",$verify);
        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $email;
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "邮箱验证内容";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;

        if ($immediately){
            $msg_data['is_send'] = 1;
        }else{
            $msg_data['is_send'] = 0;
        }
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = isset($user_info['id']) ? intval($user_info['id']) : 0;
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入

        $msg_id = $GLOBALS['db']->insert_id();

        $re['msg_id'] = $msg_id;

        if ($immediately && $msg_id > 0){
            $result = send_sms_email($msg_data);

            $re['status'] = intval($result['status']);
            $re['msg'] = trim($result['msg']);

            //发送结束，更新当前消息状态
            $GLOBALS['db']->query("update ".DB_PREFIX."deal_msg_list set is_success = ".intval($result['status']).",result='".$result['msg']."',send_time='".TIME_UTC."' where id =".$msg_id);
        }else{
            if ($msg_id == 0){
                $re['status'] = 0;
            }else{
                $re['status'] = 1;
            }
        }
        return $re;
    }else{
        return $re;
    }
}


//密码取回验证邮件
function send_user_verify_mails($email,$code,$user_info=array(),$immediately=true)
{
    $re = array('msg_id'=>0, 'status'=>0,'msg'=>'');
    if(app_conf("MAIL_ON")==1)
    {
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_USER_PASSWORD'");
        $tmpl_content = $tmpl['content'];
        $verify['email'] = $email;
        $verify['code'] = $code;
        $GLOBALS['tmpl']->assign("verify",$verify);
        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        //$msg_data['user_id'] = $user_id;
        $msg_data['dest'] = $email;
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "邮箱验证内容";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;

        if ($immediately){
            $msg_data['is_send'] = 1;
        }else{
            $msg_data['is_send'] = 0;
        }
        $msg_data['create_time'] = TIME_UTC;

        $msg_data['user_id'] = isset($user_info['id']) ? intval($user_info['id']) : 0;
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入

        $msg_id = $GLOBALS['db']->insert_id();

        $re['msg_id'] = $msg_id;

        if ($immediately && $msg_id > 0){
            $result = send_sms_email($msg_data);

            $re['status'] = intval($result['status']);
            $re['msg'] = trim($result['msg']);

            //发送结束，更新当前消息状态
            $GLOBALS['db']->query("update ".DB_PREFIX."deal_msg_list set is_success = ".intval($result['status']).",result='".$result['msg']."',send_time='".TIME_UTC."' where id =".$msg_id);
        }else{
            if ($msg_id == 0){
                $re['status'] = 0;
            }else{
                $re['status'] = 1;
            }
        }
        return $re;
    }else{
        return $re;
    }
}


//发密码验证邮件
function send_user_password_mail($user_id)
{
    if(app_conf("MAIL_ON")==1)
    {
        $verify_code = rand(111111,999999);
        $GLOBALS['db']->query("update ".DB_PREFIX."user set password_verify = '".$verify_code."' where id = ".$user_id);
        $user_info = get_user_info("*","id = ".$user_id);
        if($user_info)
        {
            $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_USER_PASSWORD'");
            $tmpl_content=  $tmpl['content'];
            $user_info['password_url'] = SITE_DOMAIN.url("index","user#modify_password", array("code"=>$user_info['password_verify'],"id"=>$user_info['id']));
            $GLOBALS['tmpl']->assign("user",$user_info);
            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
            $msg_data['dest'] = $user_info['email'];
            $msg_data['send_type'] = 1;
            $msg_data['title'] = $GLOBALS['lang']['RESET_PASSWORD'];
            $msg_data['content'] = addslashes($msg);
            $msg_data['send_time'] = 0;
            $msg_data['is_send'] = 0;
            $msg_data['create_time'] = TIME_UTC;
            $msg_data['user_id'] = $user_info['id'];
            $msg_data['is_html'] = $tmpl['is_html'];
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        }
    }
}

//发密码验证邮件--担保机构
function send_unit_user_password_mail($user_id)
{
    //if(app_conf("MAIL_ON")==1)
    //{
    $verify_code = rand(111111,999999);
    $GLOBALS['db']->query("update ".DB_PREFIX."user set code = '".$verify_code."' where id = ".$user_id);
    $user_info = get_user_info("*","id = ".$user_id);
    if($user_info)
    {
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_USER_PASSWORD'");
        $tmpl_content=  $tmpl['content'];
        $user_info['password_url'] = SITE_DOMAIN.url("index","manageagency#modify_password", array("code"=>$user_info['password_verify'],"id"=>$user_info['id']));
        $GLOBALS['tmpl']->assign("user",$user_info);
        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $user_info['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = $GLOBALS['lang']['RESET_PASSWORD'];
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $user_info['id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }
    //}
}


//发短信收款单
function send_payment_sms($notice_id)
{
    if(app_conf("SMS_ON")==1&&app_conf("SMS_SEND_PAYMENT")==1)
    {
        $notice_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment_notice where id = ".$notice_id);
        if($notice_data)
        {
            $user_info = get_user_info("*","id = ".$notice_data['user_id']);
            $order_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_order where id = ".$notice_data['order_id']);
            if($user_info['mobile']!=''||$order_info['mobile']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_PAYMENT'");
                $tmpl_content = $tmpl['content'];
                $notice_data['user_name'] = $user_info['user_name'];
                $notice_data['order_sn'] = $GLOBALS['db']->getOne("select order_sn from ".DB_PREFIX."deal_order where id = ".$notice_data['order_id']);
                $notice_data['pay_time_format'] = to_date($notice_data['pay_time']);
                $notice_data['money_format'] = format_price($notice_data['money']);
                $GLOBALS['tmpl']->assign("payment_notice",$notice_data);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                if($user_info['mobile']!='')
                {
                    $msg_data['dest'] = $user_info['mobile'];
                }
                else
                {
                    $msg_data['dest'] = $order_info['mobile'];
                }
                $msg_data['send_type'] = 0;
                $msg_data['content'] = addslashes($msg);;
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] = $user_info['id'];
                $msg_data['is_html'] = $tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入

            }
        }
    }

    if(app_conf("WEIXIN_MSG")==1){
        $notice_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment_notice where id = ".$notice_id);
        if($notice_data)
        {
            $user_info = get_user_info("*","id = ".$notice_data['user_id']);
            $order_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_order where id = ".$notice_data['order_id']);
            if($user_info['wx_openid']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM207791277' ");
                $today = to_date(TIME_UTC,"Y-m-d");
                $order_sn = $GLOBALS['db']->getOne("select order_sn from ".DB_PREFIX."deal_order where id = ".$notice_data['order_id']);
                $weixin_data['first'] = array('value'=>$user_info['user_name'].'您的订单已支付成功','color'=>'#173177');
                $weixin_data['keyword1']=array('value'=>$order_sn,'color'=>'#173177');
                $weixin_data['keyword2']=array('value'=>format_price($notice_data['money']),'color'=>'#173177');

                weixin_tmpl_send($tmpl['template_id'],$user_info['id'],$weixin_data);
            }
        }
    }
}

//发邮件收款单
function send_payment_mail($notice_id)
{
    if(app_conf("MAIL_ON")==1&&app_conf("MAIL_SEND_PAYMENT")==1)
    {
        $notice_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment_notice where id = ".$notice_id);
        if($notice_data)
        {
            $user_info = get_user_info("*","id = ".$notice_data['user_id']);
            if($user_info['email']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_PAYMENT'");
                $tmpl_content = $tmpl['content'];
                $notice_data['user_name'] = $user_info['user_name'];
                $notice_data['order_sn'] = $GLOBALS['db']->getOne("select order_sn from ".DB_PREFIX."deal_order where id = ".$notice_data['order_id']);
                $notice_data['pay_time_format'] = to_date($notice_data['pay_time']);
                $notice_data['money_format'] = format_price($notice_data['money']);
                $GLOBALS['tmpl']->assign("payment_notice",$notice_data);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = $GLOBALS['lang']['PAYMENT_NOTICE'];
                $msg_data['content'] = addslashes($msg);;
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] = $user_info['id'];
                $msg_data['is_html'] = $tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }
    }
}



//发邮件发货单
function send_delivery_mail($notice_sn,$deal_names = '',$order_id)
{
    if(app_conf("MAIL_ON")==1&&app_conf("MAIL_SEND_DELIVERY")==1)
    {
        $notice_data = $GLOBALS['db']->getRow("select dn.* from ".DB_PREFIX."delivery_notice as dn left join ".DB_PREFIX."deal_order_item as doi on dn.order_item_id = doi.id where dn.notice_sn = '".$notice_sn."' and doi.order_id = ".$order_id);
        if($notice_data)
        {
            $user_info = get_user_info("*","id = ".$notice_data['user_id']);
            if($user_info['email']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_DELIVERY'");
                $tmpl_content = $tmpl['content'];
                $notice_data['user_name'] = $user_info['user_name'];
                $notice_data['order_sn'] = $GLOBALS['db']->getOne("select do.order_sn from ".DB_PREFIX."deal_order_item as doi left join ".DB_PREFIX."deal_order as do on doi.order_id = do.id where doi.id = ".$notice_data['order_item_id']);
                $notice_data['delivery_time_format'] = to_date($notice_data['delivery_time']);
                $notice_data['deal_names'] = $deal_names;
                $GLOBALS['tmpl']->assign("delivery_notice",$notice_data);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = $GLOBALS['lang']['DELIVERY_NOTICE'];
                $msg_data['content'] = addslashes($msg);;
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] = $user_info['id'];
                $msg_data['is_html'] = $tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }
    }
}

//发短信发货单
function send_delivery_sms($notice_sn,$deal_names = '',$order_id)
{
    if(app_conf("SMS_ON")==1&&app_conf("SMS_SEND_DELIVERY")==1)
    {
        $notice_data = $GLOBALS['db']->getRow("select dn.* from ".DB_PREFIX."delivery_notice as dn left join ".DB_PREFIX."deal_order_item as doi on dn.order_item_id = doi.id where dn.notice_sn = '".$notice_sn."' and doi.order_id = ".$order_id);
        if($notice_data)
        {
            $order_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_order where id = ".$order_id);
            $user_info = get_user_info("*","id = ".$notice_data['user_id']);
            if($user_info['mobile']!=''||$order_info['mobile']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_DELIVERY'");
                $tmpl_content = $tmpl['content'];
                $notice_data['user_name'] = $user_info['user_name'];
                $notice_data['order_sn'] = $GLOBALS['db']->getOne("select do.order_sn from ".DB_PREFIX."deal_order_item as doi left join ".DB_PREFIX."deal_order as do on doi.order_id = do.id where doi.id = ".$notice_data['order_item_id']);
                $notice_data['delivery_time_format'] = to_date($notice_data['delivery_time']);
                $notice_data['deal_names'] = $deal_names;
                $GLOBALS['tmpl']->assign("delivery_notice",$notice_data);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                if($user_info['mobile']!='')
                {
                    $msg_data['dest'] = $user_info['mobile'];
                    $msg_data['send_type'] = 0;
                    $msg_data['content'] = addslashes($msg);;
                    $msg_data['send_time'] = 0;
                    $msg_data['is_send'] = 0;
                    $msg_data['create_time'] = TIME_UTC;
                    $msg_data['user_id'] = $user_info['id'];
                    $msg_data['is_html'] = $tmpl['is_html'];
                    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
                }

                if($order_info['mobile']!=''&&$order_info['mobile']!=$user_info['mobile'])
                {
                    $msg_data['dest'] = $order_info['mobile'];
                    $msg_data['send_type'] = 0;
                    $msg_data['content'] = addslashes($msg);;
                    $msg_data['send_time'] = 0;
                    $msg_data['is_send'] = 0;
                    $msg_data['create_time'] = TIME_UTC;
                    $msg_data['user_id'] = $user_info['id'];
                    $msg_data['is_html'] = $tmpl['is_html'];
                    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
                }
            }
        }
    }
}


//发短信验证码4013275
//$immediately: true，立即即行发送操作;
function send_verify_sms( $netease_template_id,$mobile,$code,$user_info=array(),$immediately=false)
{
    $re = array('msg_id'=>0, 'status'=>0,'msg'=>'');

    if(app_conf("SMS_ON")==1)
    {
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_VERIFY_CODE'");
        $tmpl_content = $tmpl['content'];
        $verify['mobile'] = $mobile;
        $verify['code'] = $code;
        $GLOBALS['tmpl']->assign("verify",$verify);
        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $mobile;
        $msg_data['mobile'] = $mobile;
        $msg_data['send_type'] = 0;
        $msg_data['title'] = addslashes($msg);
        $msg_data['content'] = $msg_data['title'];
        $msg_data['send_time'] = 0;
        $msg_data['code'] = $code;
        if ($immediately){
            $msg_data['is_send'] = 1;
        }else{
            $msg_data['is_send'] = 0;
        }
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = isset($user_info['id']) ? $user_info['id'] : 0;;
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入

        $msg_id = $GLOBALS['db']->insert_id();

        $re['msg_id'] = $msg_id;

        if ( $msg_id > 0){
            $msg_data['netease_template_id'] = $netease_template_id ;
            $result = send_sms_email($msg_data);

            $re['status'] = intval($result['status']);
            $re['msg'] = trim($result['msg']);

            //发送结束，更新当前消息状态
            $GLOBALS['db']->query("update ".DB_PREFIX."deal_msg_list set is_success = ".intval($result['status']).",result='".$result['msg']."',send_time='".TIME_UTC."' where id =".$msg_id);
        }else{
            if ($msg_id == 0){
                $re['status'] = 0;
            }else{
                $re['status'] = 1;
            }
        }
        return $re;
    }else{
        return $re;
    }
}



function send_sms_email($msg_item){

    $re = array('status'=>0,'msg'=>'');

    if($msg_item['send_type'] ==0)
    {
        //短信
        require_once APP_ROOT_PATH."system/utils/es_sms.php";
        $sms = new sms_sender();

        $result = $sms->sendSms($msg_item['netease_template_id'] ,$msg_item['dest'],$msg_item['code']);
        //发送结束，更新当前消息状态
        //$GLOBALS['db']->query("update ".DB_PREFIX."deal_msg_list set is_success = ".intval($result['status']).",result='".$result['msg']."',send_time='".TIME_UTC."' where id =".intval($msg_item['id']));

        $re['status'] = intval($result['status']);
        $re['msg'] = $result['msg'];
    }

    if($msg_item['send_type']==1)
    {
        //邮件
        require_once APP_ROOT_PATH."system/utils/es_mail.php";
        $mail = new mail_sender();

        $mail->AddAddress($msg_item['dest']);
       $mail->IsHTML($msg_item['is_html']); 				  // 设置邮件格式为 HTML
        $mail->Subject = $msg_item['title'];   // 标题
        $mail->Body = $msg_item['content'];  // 内容

        $is_success = $mail->Send();
        $result = $mail->ErrorInfo;

        //发送结束，更新当前消息状态
        $GLOBALS['db']->query("update ".DB_PREFIX."deal_msg_list set is_success = ".intval($is_success).",result='".$result."',send_time='".TIME_UTC."' where id =".intval($msg_item['id']));

        $re['status'] = intval($is_success);
        $re['msg'] = $result;
    }

    return $re;
}

//发邮件退订验证
function send_unsubscribe_mail($email)
{
    if(app_conf("MAIL_ON")==1)
    {
        if($email)
        {
            $GLOBALS['db']->query("update ".DB_PREFIX."mail_list set code = '".rand(1111,9999)."' where mail_address='".$email."' and code = ''");
            $email_item = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."mail_list where mail_address = '".$email."' and code <> ''");
            if($email_item)
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_UNSUBSCRIBE'");
                $tmpl_content = $tmpl['content'];
                $mail = $email_item;
                $mail['url'] = SITE_DOMAIN.url("index","subscribe#dounsubscribe", array("code"=>base64_encode($mail['code']."|".$mail['mail_address'])));
                $GLOBALS['tmpl']->assign("mail",$mail);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $mail['mail_address'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = $GLOBALS['lang']['MAIL_UNSUBSCRIBE'];
                $msg_data['content'] = addslashes($msg);;
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] = 0;
                $msg_data['is_html'] = $tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }
    }
}

function get_deal_cate_name($cate_id)
{
    $GLOBALS['db'] = M();
    return $GLOBALS['db']->query("select name from ".DB_PREFIX."deal_cate where id =".$cate_id);
}

function get_loan_type_name($type_id){
    $GLOBALS['db'] = M();return $GLOBALS['db']->query("select name from ".DB_PREFIX."deal_loan_type where id =".$type_id);
}

function format_price($price,$decimals=2)
{
    return app_conf("CURRENCY_UNIT")."".number_format($price,2);
}
function format_score($score)
{
    return intval($score)."".app_conf("SCORE_UNIT");
}

//utf8 字符串截取
function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr"))
    {
        $slice =  mb_substr($str, $start, $length, $charset);
        if($suffix&$slice!=$str) return $slice."…";
        return $slice;
    }
    elseif(function_exists('iconv_substr')) {
        return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix&&$slice!=$str) return $slice."…";
    return $slice;
}

/**
 *截取替换
 */
function utf_substr($str){
    $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    preg_match_all($pa, $str, $t_string);
    if(count($t_string[0])==1)
        return $str;
    if(count($t_string[0])==2)
        return cut_str($str, 1, 0).'***';
    else
        return cut_str($str, 1, 0).'***'.cut_str($str, 1, -1);
}

function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
    if($code == 'UTF-8')
    {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i< $strlen; $i++)
        {
            if($i>=$start && $i< ($start+$sublen))
            {
                if(ord(substr($string, $i, 1))>129)
                {
                    $tmpstr.= substr($string, $i, 2);
                }
                else
                {
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        return $tmpstr;
    }
}

/**
 * PHP获取字符串中英文混合长度
 * @param $str string 字符串
 * @param $$charset string 编码
 * @return 返回长度，1中文=1位，2英文=1位
 */
function strLength($str,$charset='utf-8'){
    if($charset=='utf-8') $str = iconv('utf-8','gb2312',$str);
    $num = strlen($str);
    $cnNum = 0;
    for($i=0;$i<$num;$i++){
        if(ord(substr($str,$i+1,1))>127){
            $cnNum++;
            $i++;
        }
    }
    $enNum = $num-($cnNum*2);
    $number = ($enNum/2)+$cnNum;
    return ceil($number);
}


//字符编码转换
if(!function_exists("iconv"))
{
    function iconv($in_charset,$out_charset,$str)
    {
        require 'libs/iconv.php';
        $chinese = new Chinese();
        return $chinese->Convert($in_charset,$out_charset,$str);
    }
}

//JSON兼容
if(!function_exists("json_encode"))
{
    function json_encode($data)
    {
        require_once 'libs/json.php';
        $JSON = new JSON();
        return $JSON->encode($data);
    }
}
if(!function_exists("json_decode"))
{
    function json_decode($data)
    {
        require_once 'libs/json.php';
        $JSON = new JSON();
        return $JSON->decode($data,1);
    }
}

//邮件格式验证的函数
function check_email($email)
{
    if(!preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/",$email))
    {
        return false;
    }
    else
        return true;
}

//验证手机号码
function check_mobile($mobile)
{
    if(app_conf("MOBILE_HEAD")!=""){
        $mob = substr($mobile,0,2);
        $mob_arr = explode("|",app_conf("MOBILE_HEAD"));
        if(!in_array($mob,$mob_arr))
        {
            return false;
        }
    }

    if(!empty($mobile) && !preg_match("/^\d{6,}$/",$mobile))
    {
        return false;
    }
    else
        return true;
}

/**
 * 检查身份证
 * 0失败1成功
 */
function getIDCardInfo($vStr) {
    $vCity = array(
        '11','12','13','14','15','21','22',
        '23','31','32','33','34','35','36',
        '37','41','42','43','44','45','46',
        '50','51','52','53','54','61','62',
        '63','64','65','71','81','82','91'
    );

    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return 0;

    if (!in_array(substr($vStr, 0, 2), $vCity)) return 0;

    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);

    if ($vLength == 18)
    {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }

    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return 0;
    if ($vLength == 18)
    {
        $vSum = 0;

        for ($i = 17 ; $i >= 0 ; $i--)
        {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
        }

        if($vSum % 11 != 1) return 0;
    }

    return 1;
}

//跳转
function app_redirect($url,$time=0,$msg='')
{
    if(!defined("SITE_DOMAIN"))
        define("SITE_DOMAIN",get_domain());
    //多行URL地址支持
    $url = str_replace(array("\n", "\r"), '', $url);
    if(empty($msg))
        $msg    =   "系统将在{$time}秒之后自动跳转到{$url}！";
    if (!headers_sent()) {
        // redirect
        if(0===$time) {
            if(substr($url,0,1)=="/")
            {
                header("Location:".SITE_DOMAIN.$url);
            }
            else
            {
                header("Location:".$url);
            }

        }else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    }else {
        $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if($time!=0)
            $str   .=   $msg;
        exit($str);
    }
}

//以下微信支付有调用getMConfig and get_user_has
function get_user_has($key,$value,$is_nav=0){
    $ext = "";
    if($is_nav==0){
        $ext = " `".$key."` = '".$value."'";
    }
    else{
        $ext = " `".$key."` = ".$value;
    }
    $row=$GLOBALS['db']->getRow("select * from  ".DB_PREFIX."user where $ext ");
    if($row){
        return $row;
    }else{
        return false;
    }
}

function wap_user_login($openid = 0){
    //会员自动登录及输出

    if($openid )
    {

        $userinfo = get_user_has("wx_openid",$openid);

// 		print_r($userinfo);
        $cookie_uname = $userinfo['user_name'];
        $cookie_upwd = $userinfo['user_pwd'];

        if($cookie_uname!=''&&$cookie_upwd!='')
        {
            $cookie_uname = addslashes(trim(htmlspecialchars($cookie_uname)));
            $cookie_upwd = addslashes(trim(htmlspecialchars($cookie_upwd)));
            require_once APP_ROOT_PATH."system/libs/user.php";

            auto_do_login_user($cookie_uname,$cookie_upwd,false);

        }
    }
    elseif(empty($GLOBALS['user_info']) && $class != 'login')
    {
        $cookie_uname = es_cookie::get("user_name")?es_cookie::get("user_name"):'';
        $cookie_upwd = es_cookie::get("user_pwd")?es_cookie::get("user_pwd"):'';

        if($cookie_uname!=''&&$cookie_upwd!=''&&!es_session::get("user_info"))
        {
            //logUtils::log_str("=======1=======");
            $cookie_uname = addslashes(trim(htmlspecialchars($cookie_uname)));
            $cookie_upwd = addslashes(trim(htmlspecialchars($cookie_upwd)));
            require_once APP_ROOT_PATH."system/libs/user.php";
            //require_once APP_ROOT_PATH."app/Lib/common.php";
            auto_do_login_user($cookie_uname,$cookie_upwd);

        }
    }
    else{
        $GLOBALS['user_info'] = get_user_info("*","id=".$GLOBALS['user_info']['id']);
        \es_session::set('user_info',$GLOBALS['user_info']);
    }

}



/**
 * 验证访问IP的有效性
 * @param ip地址 $ip_str
 * @param 访问页面 $module
 * @param 时间间隔 $time_span
 * @param 数据ID $id
 */
function check_ipop_limit($ip_str,$module,$time_span=0,$id=0)
{
    $op = es_session::get($module."_".$id."_ip");
    if(empty($op))
    {
        $check['ip']	=	 CLIENT_IP;
        $check['time']	=	TIME_UTC;
        es_session::set($module."_".$id."_ip",$check);
        return true;  //不存在session时验证通过
    }
    else
    {
        $check['ip']	=	 CLIENT_IP;
        $check['time']	=	TIME_UTC;
        $origin	=	es_session::get($module."_".$id."_ip");

        if($check['ip']==$origin['ip'])
        {
            if($check['time'] - $origin['time'] < $time_span)
            {
                return false;
            }
            else
            {
                es_session::set($module."_".$id."_ip",$check);
                return true;  //不存在session时验证通过
            }
        }
        else
        {
            es_session::set($module."_".$id."_ip",$check);
            return true;  //不存在session时验证通过
        }
    }
}

/**
 * 还款返利操作
 * $dlr_id  表deal_load_repay id
 * $type 0 正常借款 1众筹
 */
function get_referrals($dlr_id,$type = 0,$user_info = array(),$order_id=0){
    if($type == 0)
    {
        if(intval(app_conf("INVITE_REFERRALS_DATE")) > 0){
            $after_year =  next_replay_month(to_timespan(to_date(TIME_UTC,"Y-m-d")),-intval(app_conf("INVITE_REFERRALS_DATE")));
            $condition =" AND u.create_time >= ".$after_year." and dl.create_time  > ".$after_year."  ";
        }

        $sql = "select dlr.*,(IF (dlr.t_user_id > 0 ,dlr.t_user_id,dlr.user_id)) as f_user_id,dl.create_time f_create_time,u.create_time,(dlr.true_interest_money * u.referral_rate * 0.01 ) as smoney,(dlr.true_self_money * u.referral_rate * 0.01 ) as ssmoney,u.user_name,u.referral_rate,u.pid " .
            "from ".DB_PREFIX."deal_load_repay dlr " .
            "LEFT JOIN ".DB_PREFIX."user u ON u.id=(IF (dlr.t_user_id > 0 ,dlr.t_user_id,dlr.user_id)) " .
            "LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id=dlr.load_id " .
            "where u.pid > 0 AND dlr.id = ".$dlr_id." AND u.referral_rate > 0 and u.user_type in (0,1) $condition ";
        $referrals_data = $GLOBALS['db']->getRow($sql);
        if((floatval($referrals_data['smoney']) != 0 && intval(app_conf("INVITE_REFERRALS_TYPE")) ==0) || (floatval($referrals_data['ssmoney']) != 0 && intval(app_conf("INVITE_REFERRALS_TYPE")) > 0))
        {
            $data['deal_id'] = $referrals_data['deal_id'];
            $data['load_id'] = $referrals_data['load_id'];
            $data['l_key'] = $referrals_data['l_key'];
            $data['money'] = intval(app_conf("INVITE_REFERRALS_TYPE")) ==0 ? $referrals_data['smoney'] : $referrals_data['ssmoney'];
            $data['user_id'] = $referrals_data['f_user_id'];
            $data['rel_user_id'] = $referrals_data['pid'];
            $data['referral_type'] = intval(app_conf("INVITE_REFERRALS_TYPE")) ==0 ? 0 : 1;
            $data['referral_rate'] = $referrals_data['referral_rate'];
            $data['repay_time'] = $referrals_data['repay_time'];
            $data['create_time'] = TIME_UTC;
            $GLOBALS['db']->autoExecute(DB_PREFIX."referrals",$data,"INSERT");
            $id = $GLOBALS['db']->insert_id();
            if($id > 0)
            {
                if(intval(app_conf("INVITE_REFERRALS_AUTO")) == 1){
                    //开始发放返利
                    require_once APP_ROOT_PATH."system/libs/user.php";

                    $lkey = $referrals_data['l_key'] + 1;
                    $referral_amount = $data['money']>0?format_price($data['money']):0;
                    require_once APP_ROOT_PATH."app/Lib/deal.php";
                    $deal = get_deal($referrals_data['deal_id']);
                    $msg = '[<a href="'.$deal['url'].'" target="_blank">'.$deal['name'].'</a>],第'.$lkey.'期,还款获取邀请返利';
                    modify_account(array('money'=>round($data['money'],2)),$referrals_data['pid'],$msg,23);
                    $GLOBALS['db']->query("UPDATE ".DB_PREFIX."referrals  SET pay_time=".TIME_UTC." WHERE id=".$id);
                }

                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    elseif($type==1)
    {
        $referrals_limit=intval(app_conf("REFERRAL_LIMIT"));
        if(intval(app_conf("BUY_INVITE_REFERRALS")) >0 && ( ($user_info['referral_count'] < $referrals_limit && $referrals_limit >0) || $referrals_limit<=0 ) )
        {
            $referral_ip_limit=app_conf("REFERRAL_IP_LIMI");//返利的IP限制
            if($referral_ip_limit ==1)//ip限制
            {
                $parent_info = $GLOBALS['db']->getRow("select login_ip,user_name from ".DB_PREFIX."user where id = ".$user_info['pid']);
                $referrals_data['user_name']=$parent_info['user_name'];
            }
            if(($referral_ip_limit ==1 && $parent_info['login_ip'] != CLIENT_IP) || $referral_ip_limit==0)
            {
                $referrals_data['user_id']=$user_info['id'];
                $referrals_data['rel_user_id']=$user_info['pid'];
                $referrals_data['score']=intval(app_conf("BUY_INVITE_REFERRALS"));
                $referrals_data['deal_id']=intval($order_id);
                $referrals_data['deal_type']=1;//0：注册奖励,1：购买奖励
                $referrals_data['create_time']= TIME_UTC;
                $referrals_data['referral_type'] = intval(app_conf("INVITE_REFERRALS_TYPE")) ==0 ? 0 : 1;
                //$referrals_data['repay_time'] = TIME_UTC;

                $GLOBALS['db']->autoExecute(DB_PREFIX."referrals",$referrals_data,"INSERT");

                $id = $GLOBALS['db']->insert_id();

                if($id > 0)
                {
                    if(intval(app_conf("INVITE_REFERRALS_AUTO")) == 1){
                        //开始发放返利
                        require_once APP_ROOT_PATH."system/libs/user.php";

                        $msg = '众筹邀请会员'.$user_info['user_name']."订单支付成功，所得奖励";

                        modify_account(array('score'=>round($referrals_data['score'],2)),$referrals_data['pid'],$msg,52);

                        modify_account(array('point'=>round($referrals_data['score'],2)),$referrals_data['pid'],$msg,52);

                        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."referrals  SET pay_time=".TIME_UTC." WHERE id=".$id);

                        //$insert_referrals_id=add_referrals($referrals_data,1);//创建返利
                        //更新会员购买返利次数
                        $GLOBALS['db']->query("update ".DB_PREFIX."user set referral_count = referral_count +1 where id =".intval($user_info['id']));

                    }

                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


    }
}
/**
 * 手动返利操作
 * $id  标 referrals id
 */
function pay_referrals($id)
{
    $sql = "select * from ".DB_PREFIX."referrals where id = ".$id;
    $referrals_data = $GLOBALS['db']->getRow($sql);

    if($referrals_data["deal_type"]==0)
    {
        if(floatval($referrals_data['money']) != 0)
        {
            //开始发放返利
            require_once APP_ROOT_PATH."system/libs/user.php";
            $lkey = $referrals_data['l_key'] + 1;
            $referral_amount = format_price($referrals_data['money']);
            require_once(APP_ROOT_PATH."app/Lib/common.php");
            require_once APP_ROOT_PATH."app/Lib/deal.php";
            $deal = get_deal($referrals_data['deal_id']);

            $msg = '[<a href="'.$deal['url'].'" target="_blank">'.$deal['name'].'</a>],第'.$lkey.'期,还款获取邀请返利';
            modify_account(array('money'=>$referrals_data['money']),$referrals_data['rel_user_id'],$msg,23);
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."referrals  SET pay_time=".TIME_UTC." WHERE id=".$id);
            return true;

        }
        else
        {
            return false;
        }
    }
    elseif($referrals_data["deal_type"]==1)
    {
        if($referrals_data['score'] != 0)
        {
            //开始发放返利
            require_once APP_ROOT_PATH."system/libs/user.php";

            $user_info = get_user_info("*"," id = ".$referrals_data["rel_user_id"]);

            $msg = '众筹邀请会员'.$user_info['user_name']."订单支付成功，所得奖励";

            modify_account(array('score'=>round($referrals_data['score'],2)),$referrals_data['rel_user_id'],$msg,52);

            modify_account(array('point'=>round($referrals_data['score'],2)),$referrals_data['rel_user_id'],$msg,52);

            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."referrals SET pay_time=".TIME_UTC." WHERE id=".$id);

            //$insert_referrals_id=add_referrals($referrals_data,1);//创建返利
            //更新会员购买返利次数
            $GLOBALS['db']->query("update ".DB_PREFIX."user set referral_count = referral_count +1 where id =".intval($user_info['id']));

            return true;
        }
        else
        {
            return false;
        }
    }

}

/**
 * 部门提成操作
 * $deal 贷款信息  $loan 投标信息
 */
function pay_manage_referrals($deal,$loan){
    if(!$deal || !$loan){
        return false;
    }
    $user_info = get_user_info("*","id=".$loan['user_id']);
    if($user_info['admin_id'] == 0)
        return false;

    //部门成员
    $mymanager = $GLOBALS['db']->getRow("SELECT id,referrals_rate,pid FROM ".DB_PREFIX."admin WHERE id=".$user_info['admin_id']);
    if($mymanager && floatval($mymanager['referrals_rate'])!=0){
        $money = 0;
        if($deal['repay_time_type'] == 0){
            //天 投资金额 × 投资的天数 / 365天
            $money = $loan['money'] * $deal['repay_time'] / 365;
        }
        else{
            //月标：投资金额 × 投资的月数 / 12个月
            $money = $loan['money'] * $deal['repay_time'] / 12;
        }

        $memo = "[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],满标放款";

        $m_data['deal_id'] = $deal['id'];
        $m_data['user_id'] = $user_info['id'];
        $m_data['money'] = $money * floatval($mymanager['referrals_rate']) * 0.01;
        $m_data['rel_admin_id'] = 0;
        $m_data['admin_id'] = $mymanager['id'];
        $m_data['rel_admin_id'] = $mymanager['pid'];
        $m_data['create_time'] = TIME_UTC;
        $m_data['create_date'] = to_date(TIME_UTC);
        $m_data['loan_money'] = $loan['money'];
        $m_data['memo'] = $memo;

        $GLOBALS['db']->autoExecute(DB_PREFIX."admin_referrals",$m_data,"INSERT");
        $GLOBALS['db']->query("update ".DB_PREFIX."admin SET referrals_money = (SELECT sum(money) FROM ".DB_PREFIX."admin_referrals WHERE admin_id=".$mymanager['id'].") WHERE id=".$mymanager['id']);

        //部门
        if($mymanager['pid'] > 0){
            $mydepartment = $GLOBALS['db']->getRow("SELECT referrals_rate,pid FROM ".DB_PREFIX."admin WHERE id=".$mymanager['pid']);

            $d_data['deal_id'] = $deal['id'];
            $d_data['user_id'] = $user_info['id'];
            $d_data['money'] = $m_data['money'] * floatval($mydepartment['referrals_rate']) * 0.01;
            $d_data['rel_admin_id'] = $user_info['admin_id'];
            $d_data['admin_id'] = $mymanager['pid'];
            $d_data['create_time'] = TIME_UTC;
            $d_data['create_date'] = to_date(TIME_UTC);
            $d_data['loan_money'] = $loan['money'];
            $d_data['memo'] = $memo;

            $GLOBALS['db']->autoExecute(DB_PREFIX."admin_referrals",$d_data,"INSERT");
            $GLOBALS['db']->query("update ".DB_PREFIX."admin SET referrals_money = (SELECT sum(money) FROM ".DB_PREFIX."admin_referrals WHERE admin_id=".$mymanager['pid'].") WHERE id=".$mymanager['pid']);
        }
    }

}


function get_deal_mail_content($deal_rs)
{
    $tmpl_content = file_get_contents(APP_ROOT_PATH."app/Tpl/".app_conf("TEMPLATE")."/deal_mail.html");
    $GLOBALS['tmpl']->assign("APP_ROOT",APP_ROOT);
    $tmpl_path = app_conf("TMPL_DOMAIN_ROOT")==''?SITE_DOMAIN.APP_ROOT:app_conf("TMPL_DOMAIN_ROOT")."/";
    if($deal_rs)
    {
        foreach($deal_rs as $k=>$deal)
        {
            $send_date = to_date(TIME_UTC,'Y年m月d日');
            $weekarray = array("日","一","二","三","四","五","六");
            $send_date .= " 星期".$weekarray[to_date(TIME_UTC,"w")];
            $deal['send_date'] = $send_date;
            $deal['url'] = $tmpl_path.url("index","deal",array("id"=>$deal['id']));
            $deal['borrow_amount_format'] = $deal_rs[$k]['borrow_amount'];
            $deal['rate_foramt'] = $deal_rs[$k]['rate'];
            $deal['rate_foramt'] = $deal_rs[$k]['type_match_row'];
            $deal_rs[$k] = $deal;
        }
        $GLOBALS['tmpl']->assign("deal_rs",$deal_rs);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        //$tmpl_path = app_conf("TMPL_DOMAIN_ROOT")==''?SITE_DOMAIN.APP_ROOT."/app/Tpl/":app_conf("TMPL_DOMAIN_ROOT")."/";
        $content = str_replace("deal_mail/",$tmpl_path.app_conf("TEMPLATE")."/deal_mail/",$content);
        //print_r($deal_rs);die;
        return $content;
    }
    else
        return '';
}



/**
 * $notice.site_name
 * $notice.deal_name
 * $notice.site_url
 * @param $deal_id
 */
function get_deal_sms_content($deal_id)
{
    $tmpl_content = $GLOBALS['db']->getOne("select content from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_NOTICE_SMS'");
    $deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);
    if($deal)
    {
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['deal_name'] = $deal['sub_name'];
        $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
        $GLOBALS['tmpl']->assign("notice",$notice);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        return $content;
    }
    else
        return '';
}

/**
 * $bond.sn
 * $bond.password
 * $bond.name
 * $bond.user_name
 * $bond.begin_time_format
 * $bond.end_time_format
 * $bond.tel
 * $bond.address
 * $bond.route
 * $bond.open_time
 * @param $coupon_id
 * @param $location_id
 */


function gzip_out($content)
{
    header("Content-type: text/html; charset=utf-8");
    header("Cache-control: private");  //支持页面回跳
    $gzip = app_conf("GZIP_ON");
    if( intval($gzip)==1 )
    {
        if(!headers_sent()&&extension_loaded("zlib")&&preg_match("/gzip/i",$_SERVER["HTTP_ACCEPT_ENCODING"]))
        {
            $content = gzencode($content,9);
            header("Content-Encoding: gzip");
            header("Content-Length: ".strlen($content));
            echo $content;
        }
        else
            echo $content;
    }else{
        echo $content;
    }

}

function order_log($log_info,$order_id)
{
    $data['id'] = 0;
    $data['log_info'] = $log_info;
    $data['log_time'] = TIME_UTC;
    $data['order_id'] = $order_id;
    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_order_log", $data);
}


/**
 * 保存图片
 * @param array $upd_file  即上传的$_FILES数组
 * @param array $key $_FILES 中的键名 为空则保存 $_FILES 中的所有图片
 * @param string $dir 保存到的目录
 * @param array $whs
可生成多个缩略图
数组 参数1 为宽度，
参数2为高度，
参数3为处理方式:0(缩放,默认)，1(剪裁)，
参数4为是否水印 默认为 0(不生成水印)
array(
'thumb1'=>array(300,300,0,0),
'thumb2'=>array(100,100,0,0),
'origin'=>array(0,0,0,0),  宽与高为0为直接上传
...
)，
 * @param array $is_water 原图是否水印
 * @return array
array(
'key'=>array(
'name'=>图片名称，
'url'=>原图web路径，
'path'=>原图物理路径，
有略图时
'thumb'=>array(
'thumb1'=>array('url'=>web路径,'path'=>物理路径),
'thumb2'=>array('url'=>web路径,'path'=>物理路径),
...
)
)
....
)
 */
//$img = save_image_upload($_FILES,'avatar','temp',array('avatar'=>array(300,300,1,1)),1);
function save_image_upload($upd_file, $key='',$dir='temp', $whs=array(),$is_water=false,$need_return = false)
{
    require_once APP_ROOT_PATH."system/utils/es_imagecls.php";
    $image = new es_imagecls();
    $image->max_size = intval(app_conf("MAX_IMAGE_SIZE"));

    $list = array();

    if(empty($key))
    {
        foreach($upd_file as $fkey=>$file)
        {
            $list[$fkey] = false;
            $image->init($file,$dir);
            if($image->save())
            {
                $list[$fkey] = array();
                $list[$fkey]['url'] = $image->file['target'];
                $list[$fkey]['path'] = $image->file['local_target'];
                $list[$fkey]['name'] = $image->file['prefix'];
            }
            else
            {
                if($image->error_code==-105)
                {
                    if($need_return)
                    {
                        return array('error'=>1,'message'=>'上传的图片太大');
                    }
                    else
                        echo "上传的图片太大";
                }
                elseif($image->error_code==-104||$image->error_code==-103||$image->error_code==-102||$image->error_code==-101)
                {
                    if($need_return)
                    {
                        return array('error'=>1,'message'=>'非法图像');
                    }
                    else
                        echo "非法图像";
                }
                exit;
            }
        }
    }
    else
    {
        $list[$key] = false;
        $image->init($upd_file[$key],$dir);
        if($image->save())
        {
            $list[$key] = array();
            $list[$key]['url'] = $image->file['target'];
            $list[$key]['path'] = $image->file['local_target'];
            $list[$key]['name'] = $image->file['prefix'];
        }
        else
        {
            if($image->error_code==-105)
            {
                if($need_return)
                {
                    return array('error'=>1,'message'=>'上传的图片太大');
                }
                else
                    echo "上传的图片太大";
            }
            elseif($image->error_code==-104||$image->error_code==-103||$image->error_code==-102||$image->error_code==-101)
            {
                if($need_return)
                {
                    return array('error'=>1,'message'=>'非法图像');
                }
                else
                    echo "非法图像";
            }
            exit;
        }
    }

    $water_image = APP_ROOT_PATH.app_conf("WATER_MARK");
    $alpha = app_conf("WATER_ALPHA");
    $place = app_conf("WATER_POSITION");

    foreach($list as $lkey=>$item)
    {
        //循环生成规格图
        foreach($whs as $tkey=>$wh)
        {
            $list[$lkey]['thumb'][$tkey]['url'] = false;
            $list[$lkey]['thumb'][$tkey]['path'] = false;
            if($wh[0] > 0 || $wh[1] > 0)  //有宽高度
            {
                $thumb_type = isset($wh[2]) ? intval($wh[2]) : 0;  //剪裁还是缩放， 0缩放 1剪裁
                if($thumb = $image->thumb($item['path'],$wh[0],$wh[1],$thumb_type))
                {
                    $list[$lkey]['thumb'][$tkey]['url'] = $thumb['url'];
                    $list[$lkey]['thumb'][$tkey]['path'] = $thumb['path'];
                    if(isset($wh[3]) && intval($wh[3]) > 0)//需要水印
                    {
                        $paths = pathinfo($list[$lkey]['thumb'][$tkey]['path']);
                        $path = $paths['dirname'];
                        $path = $path."/origin/";
                        if (!is_dir($path)) {
                            @mkdir($path);
                            @chmod($path, 0777);
                        }
                        $filename = $paths['basename'];
                        @file_put_contents($path.$filename,@file_get_contents($list[$lkey]['thumb'][$tkey]['path']));
                        $image->water($list[$lkey]['thumb'][$tkey]['path'],$water_image,$alpha, $place);
                    }
                }
            }
        }
        if($is_water)
        {
            $paths = pathinfo($item['path']);
            $path = $paths['dirname'];
            $path = $path."/origin/";
            if (!is_dir($path)) {
                @mkdir($path);
                @chmod($path, 0777);
            }
            $filename = $paths['basename'];
            @file_put_contents($path.$filename,@file_get_contents($item['path']));
            $image->water($item['path'],$water_image,$alpha, $place);
        }
    }
    return $list;
}

function empty_tag($string)
{
    $string = preg_replace(array("/\[img\]\d+\[\/img\]/","/\[[^\]]+\]/"),array("",""),$string);
    if(trim($string)=='')
        return $GLOBALS['lang']['ONLY_IMG'];
    else
        return $string;
    //$string = str_replace(array("[img]","[/img]"),array("",""),$string);
}

//验证是否有非法字汇，未完成
function valid_str($string)
{
    $string = msubstr($string,0,5000);
    if(app_conf("FILTER_WORD")!='')
        $string = preg_replace("/".app_conf("FILTER_WORD")."/","*",$string);
    return $string;
}


/**
 * utf8字符转Unicode字符
 * @param string $char 要转换的单字符
 * @return void
 */
function utf8_to_unicode($char)
{
    switch(strlen($char))
    {
        case 1:
            return ord($char);
        case 2:
            $n = (ord($char[0]) & 0x3f) << 6;
            $n += ord($char[1]) & 0x3f;
            return $n;
        case 3:
            $n = (ord($char[0]) & 0x1f) << 12;
            $n += (ord($char[1]) & 0x3f) << 6;
            $n += ord($char[2]) & 0x3f;
            return $n;
        case 4:
            $n = (ord($char[0]) & 0x0f) << 18;
            $n += (ord($char[1]) & 0x3f) << 12;
            $n += (ord($char[2]) & 0x3f) << 6;
            $n += ord($char[3]) & 0x3f;
            return $n;
    }
}

/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @param string $depart 分隔,默认为空格为单字
 * @return string
 */
function str_to_unicode_word($str,$depart=' ')
{
    $arr = array();
    $str_len = mb_strlen($str,'utf-8');
    for($i = 0;$i < $str_len;$i++)
    {
        $s = mb_substr($str,$i,1,'utf-8');
        if($s != ' ' && $s != '　')
        {
            $arr[] = 'ux'.utf8_to_unicode($s);
        }
    }
    return implode($depart,$arr);
}


/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @return string
 */
function str_to_unicode_string($str)
{
    $string = str_to_unicode_word($str,'');
    return $string;
}

//分词
function div_str($str)
{
    require_once APP_ROOT_PATH."system/libs/words.php";
    $words = words::segment($str);
    $words[] = $str;
    return $words;
}


/**
 *
 * @param $tag  //要插入的关键词
 * @param $table  //表名
 * @param $id  //数据ID
 * @param $field		// tag_match/name_match/cate_match/locate_match
 */
function insert_match_item($tag,$table,$id,$field)
{
    if($tag=='')
        return;

    $unicode_tag = str_to_unicode_string($tag);
    $sql = "select count(*) from ".DB_PREFIX.$table." where match(".$field.") against ('".$unicode_tag."' IN BOOLEAN MODE) and id = ".$id;
    $rs = $GLOBALS['db']->getOne($sql);
    if(intval($rs) == 0)
    {
        $match_row = $GLOBALS['db']->getRow("select * from ".DB_PREFIX.$table." where id = ".$id);
        if($match_row[$field]=="")
        {
            $match_row[$field] = $unicode_tag;
            $match_row[$field."_row"] = $tag;
        }
        else
        {
            $match_row[$field] = $match_row[$field].",".$unicode_tag;
            $match_row[$field."_row"] = $match_row[$field."_row"].",".$tag;
        }
        $GLOBALS['db']->autoExecute(DB_PREFIX.$table, $match_row, $mode = 'UPDATE', "id=".$id, $querymode = 'SILENT');

    }
}

function get_all_parent_id($id,$table,&$arr = array())
{
    if(intval($id)>0)
    {
        $arr[] = $id;
        $pid = $GLOBALS['db']->getOne("select pid from ".$table." where id = ".$id);
        if($pid>0)
        {
            get_all_parent_id($pid,$table,$arr);
        }
    }
}

function syn_deal_match($deal_id)
{
    $deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);
    if($deal)
    {
        $deal['name_match'] = "";
        $deal['name_match_row'] = "";
        $deal['deal_cate_match'] = "";
        $deal['deal_cate_match_row'] = "";
        $deal['type_match'] = "";
        $deal['type_match_row'] = "";
        $deal['tag_match'] = "";
        $deal['tag_match_row'] = "";
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal", $deal, $mode = 'UPDATE', "id=".$deal_id, $querymode = 'SILENT');

        //同步名称
        $name_arr = div_str(trim($deal['name']));
        foreach($name_arr as $name_item)
        {
            insert_match_item($name_item,"deal",$deal_id,"name_match");
        }

        //分类类别
        $deal_cate =array();
        get_all_parent_id(intval($deal['cate_id']),DB_PREFIX."deal_cate",$deal_cate);
        if(count($deal_cate)>0)
        {
            $deal_cates = $GLOBALS['db']->getAll("select name from ".DB_PREFIX."deal_cate where id in (".implode(",",$deal_cate).")");
            foreach ($deal_cates as $row)
            {
                insert_match_item(trim($row['name']),"deal",$deal_id,"deal_cate_match");
            }
        }
        $goods_cate =array();
        get_all_parent_id(intval($deal['type_id']),DB_PREFIX."deal_loan_type",$goods_cate);
        if(count($goods_cate)>0)
        {
            $goods_cates = $GLOBALS['db']->getAll("select name from ".DB_PREFIX."deal_loan_type where id in (".implode(",",$goods_cate).")");
            foreach ($goods_cates as $row)
            {
                insert_match_item(trim($row['name']),"deal",$deal_id,"type_match");
            }
        }


    }
}


//封装url

function url($app_index,$route="index",$param=array())
{
    $key = md5("URL_KEY_".$app_index.$route.serialize($param));
    if (isset($GLOBALS['request']) && $GLOBALS['request']['from']!="wap"){
        if(isset($GLOBALS[$key]))
        {
            $url = $GLOBALS[$key];
            return $url;
        }

        $url = load_dynamic_cache($key);
        if($url!==false)
        {
            $GLOBALS[$key] = $url;
            return $url;
        }
    }

    $route_array = explode("#",$route);

    if(isset($param)&&$param!=''&&!is_array($param))
    {
        $param['id'] = $param;
    }

    $module = isset($route_array[0]) ? (trim($route_array[0]) ? strtolower(trim($route_array[0])) : "") : "";
    $action = isset($route_array[1]) ? (trim($route_array[1]) ? strtolower(trim($route_array[1])) : "") : "";

    if(!$module||$module=='index')$module="";
    if(!$action||$action=='index')$action="";

    if(app_conf("URL_MODEL")==0 || $GLOBALS['request']['from']=="wap")
    {
        //过滤主要的应用url
        if($app_index==app_conf("MAIN_APP"))
            $app_index = "index";
        if(substr($module,0,3)=="uc_"){
            $app_index = "member";
        }

        //原始模式
        if($GLOBALS['request']['from']=="wap"){

            if(strpos(APP_ROOT,"/wap")===false)
                $url = APP_ROOT."/wap"."/".$app_index.".php";
            else
                $url = APP_ROOT."/".$app_index.".php";
        }
        else
            $url = APP_ROOT."/".$app_index.".php";


        if($module!=''||$action!=''||count($param)>0) //有后缀参数
        {
            $url.="?";
        }


        if($module&&$module!='')
            $url .= "ctl=".$module."&";
        if($action&&$action!='')
            $url .= "act=".$action."&";
        if(count($param)>0)
        {
            foreach($param as $k=>$v)
            {
                if($k&&$v)
                    $url =$url.$k."=".urlencode($v)."&";
            }
        }
        if(substr($url,-1,1)=='&'||substr($url,-1,1)=='?') $url = substr($url,0,-1);

        $url = str_replace("/mapi/","/",$url);
        if (isset($GLOBALS['request']) && $GLOBALS['request']['from']!="wap"){
            $GLOBALS[$key] = $url;
            set_dynamic_cache($key,$url);
        }

        $GLOBALS['request']['from']="index";
        return $url;
    }
    else
    {
        //重写的默认
        $url = APP_ROOT;

        if($app_index!='index')
            $url .= "/".$app_index;

        if($module&&$module!='')
            $url .= "/".$module;
        if($action&&$action!='')
            $url .= "-".$action;

        if(count($param)>0)
        {
            $url.="/";
            foreach($param as $k=>$v)
            {
                $url =$url.$k."-".urlencode($v)."-";
            }
        }

        //过滤主要的应用url
        if($app_index==app_conf("MAIN_APP"))
            $url = str_replace("/".app_conf("MAIN_APP"),"",$url);

        $route = $module."#".$action;
        switch ($route)
        {
            case "xxx":
                break;
            default:
                break;
        }

        if(substr($url,-1,1)=='/'||substr($url,-1,1)=='-') $url = substr($url,0,-1);

        $url = str_replace("/mapi/","/",$url);

        if($url=='')$url="/";

        $GLOBALS[$key] = $url;
        set_dynamic_cache($key,$url);

        $GLOBALS['request']['from']="index";
        return $url;
    }


}


//wap重写下使用原始链接
function wap_url($app_index="index",$route="index",$param=array())
{
    $GLOBALS['request']['from'] = "wap";
    return U($route.'/'.$app_index ,$param) ;
    //return url($app_index,$route,$param);
}


function unicode_encode($name) {//to Unicode
    $name = iconv('UTF-8', 'UCS-2', $name);
    $len = strlen($name);
    $str = '';
    for($i = 0; $i < $len - 1; $i = $i + 2) {
        $c = $name[$i];
        $c2 = $name[$i + 1];
        if (ord($c) > 0) {// 两个字节的字
            $cn_word = '\\'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
            $str .= strtoupper($cn_word);
        } else {
            $str .= $c2;
        }
    }
    return $str;
}

function unicode_decode($name) {//Unicode to
    $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
    preg_match_all($pattern, $name, $matches);
    if (!empty($matches)) {
        $name = '';
        for ($j = 0; $j < count($matches[0]); $j++) {
            $str = $matches[0][$j];
            if (strpos($str, '\\u') === 0) {
                $code = base_convert(substr($str, 2, 2), 16, 10);
                $code2 = base_convert(substr($str, 4), 16, 10);
                $c = chr($code).chr($code2);
                $c = iconv('UCS-2', 'UTF-8', $c);
                $name .= $c;
            } else {
                $name .= $str;
            }
        }
    }
    return $name;
}


//载入动态缓存数据
function load_dynamic_cache($name)
{
    if(isset($GLOBALS['dynamic_cache'][$name]))
    {
        return $GLOBALS['dynamic_cache'][$name];
    }
    else
    {
        return false;
    }
}

function set_dynamic_cache($name,$value)
{
    if(!isset($GLOBALS['dynamic_cache'][$name]))
    {
        if(count($GLOBALS['dynamic_cache'])>MAX_DYNAMIC_CACHE_SIZE)
        {
            array_shift($GLOBALS['dynamic_cache']);
        }
        $GLOBALS['dynamic_cache'][$name] = $value;
    }
}


function load_auto_cache($key,$param=array())
{
    $check_array =  array(
        "cache_deal_cate",
        "cache_money_type",
        "cache_nav_list",
        "cache_shop_acate_tree",
        "consignee_info",
        "contract_cache",
        "credit_type",
        "deal_city",
        "deal_loan_type_list",
        "deal_shop_acate_belone_ids",
        "deal_sub_cate_ids",
        "deal_sub_parent_cate_ids",
        "expression_replace_array",
        "expression_replace_none_array",
        "get_help_cache",
        "level",
        "links",
        "loantype_list",
        "page_image",
        "score_cates",
        "user_carry_config",
        "user_field_list",
        "vip_list",
        "weixin_conf",
    );
    if(in_array($key, $check_array))
    {
        require_once APP_ROOT_PATH."system/libs/auto_cache.php";
        $file =  APP_ROOT_PATH."system/auto_cache/".$key.".auto_cache.php";

        require_once $file;
        $class = $key."_auto_cache";
        $obj = new $class;
        $result = $obj->load($param);
    }
    else
        $result = false;
    return $result;
}

function rm_auto_cache($key,$param=array())
{
    require_once APP_ROOT_PATH."system/libs/auto_cache.php";
    $file =  APP_ROOT_PATH."system/auto_cache/".$key.".auto_cache.php";
    if(file_exists($file))
    {
        require_once $file;
        $class = $key."_auto_cache";
        $obj = new $class;
        $obj->rm($param);
    }
}


function clear_auto_cache($key)
{
    require_once APP_ROOT_PATH."system/libs/auto_cache.php";
    $file =  APP_ROOT_PATH."system/auto_cache/".$key.".auto_cache.php";
    if(file_exists($file))
    {
        require_once $file;
        $class = $key."_auto_cache";
        $obj = new $class;
        $obj->clear_all();
    }
}

//获取随机会员提供关注
function get_rand_user($count,$is_daren=0,$uid=0)
{
    /*//第0阶梯达人，10个会员
	$danren_result_0 = $GLOBALS['cache']->get("RAND_USER_CACHE_DAREN_0");
	if($danren_result_0===false)
	{
		$sql = "select id,user_name,province_id,city_id from ".DB_PREFIX."user where is_daren = 1 order by is_merchant desc,is_daren desc,topic_count desc limit 10";
		$danren_result_0 = $GLOBALS['db']->getAll($sql);
		if($danren_result_0)
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_0",$danren_result_0,3600);
		else
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_0",array(),3600);
	}

	//第1阶梯达人，50个会员
	$danren_result_1 = $GLOBALS['cache']->get("RAND_USER_CACHE_DAREN_1");
	if($danren_result_1===false)
	{
		$sql = "select id,user_name,province_id,city_id from ".DB_PREFIX."user where is_daren = 1 order by is_merchant desc,is_daren desc,topic_count desc limit 10,50";
		$danren_result_1 = $GLOBALS['db']->getAll($sql);
		if($danren_result_1)
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_1",$danren_result_1,3600);
		else
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_1",array(),3600);
	}

	//第2阶梯达人，2000个会员
	$danren_result_2 = $GLOBALS['cache']->get("RAND_USER_CACHE_DAREN_2");
	if($danren_result_2===false)
	{
		$sql = "select id,user_name,province_id,city_id from ".DB_PREFIX."user where is_daren = 1 order by is_merchant desc,is_daren desc,topic_count desc limit 50,2000";
		$danren_result_2 = $GLOBALS['db']->getAll($sql);
		if($danren_result_2)
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_2",$danren_result_2,3600);
		else
		$GLOBALS['cache']->set("RAND_USER_CACHE_DAREN_2",array(),3600);
	}

	$danren_list[] = $danren_result_0;
	$danren_list[] = $danren_result_1;
	$danren_list[] = $danren_result_2;

	//非达人 , 2000个活跃会员
	$nodanren_result = $GLOBALS['cache']->get("RAND_USER_CACHE_NODAREN");
	if($nodanren_result===false)
	{
		$sql = "select id,user_name,province_id,city_id from ".DB_PREFIX."user where is_daren = 0 order by is_merchant desc,is_daren desc,topic_count desc limit 2000";
		$nodanren_result = $GLOBALS['db']->getAll($sql);
		if($nodanren_result)
		$GLOBALS['cache']->set("RAND_USER_CACHE_NODAREN",$nodanren_result,3600);
		else
		$GLOBALS['cache']->set("RAND_USER_CACHE_NODAREN",array(),3600);
	}

	$user_list = array();
	if($uid==0)
	{
		$user_group = 0; //阶梯数
		while(count($user_list)<$count&&$user_group<3)
		{
			$current_count = count($user_list);
			for($loop=0;$loop<$count-$current_count;$loop++)
			{
				$i = rand(0,count($danren_list[$user_group])-1);
				$user_item = $danren_list[$user_group][$i];
				unset($danren_list[$user_group][$i]);
				sort($danren_list[$user_group]);
				if($user_item)
				$user_list[] = $user_item;
			}
			$user_group++;
		}

		if(count($user_list)<$count&&$is_daren==0)
		{
			//人数还不足，并允许非达人
			$current_count = count($user_list);
			for($loop=0;$loop<$count-$current_count;$loop++)
			{
				$i = rand(0,count($nodanren_result)-1);
				$user_item = $nodanren_result[$i];
				unset($nodanren_result[$i]);
				sort($nodanren_result);
				if($user_item)
				$user_list[] = $user_item;
			}
		}

	}
	else
	{


		$user_group = 0; //阶梯数
		while(count($user_list)<$count&&$user_group<3)
		{
			$current_count = count($user_list);
			//$loop_count 用于限制循环上限, $c用于计算个数, $i标识当前位置
			for($loop_count=0,$c=0;$c<$count-$current_count&&$loop_count<100;$loop_count++,$c++)
			{
				$i = rand(0,count($danren_list[$user_group])-1);
				$user_item = $danren_list[$user_group][$i];
				unset($danren_list[$user_group][$i]);
				sort($danren_list[$user_group]);
				if($user_item)
				{
					if($user_item['id']!=$uid&&$GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_focus where focus_user_id=".$uid." and focused_user_id = ".intval($user_item['id']))==0)
					$user_list[] = $user_item;
					else
					$c--;
				}

			}
			$user_group++;
		}

		if(count($user_list)<$count&&$is_daren==0)
		{
			//人数还不足，并允许非达人

			$current_count = count($user_list);
			for($loop_count=0,$c=0;$c<$count-$current_count&&$loop_count<100;$loop_count++,$c++)
			{
				$i = rand(0,count($nodanren_result)-1);
				$user_item = $nodanren_result[$i];
				unset($nodanren_result[$i]);
				sort($nodanren_result);
				if($user_item)
				{
					if($user_item['id']!=$uid&&$GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_focus where focus_user_id=".$uid." and focused_user_id = ".intval($user_item['id']))==0)
					$user_list[] = $user_item;
					else
					$c--;
				}
			}
		}

	}
	return $user_list;
	*/
}

/*ajax返回*/
function ajax_return($data)
{
    header("Content-Type:text/html; charset=utf-8");
    echo(json_encode($data));
    exit;
}


//增加会员活跃度
function increase_user_active($user_id,$log)
{
    $t_begin_time = to_timespan(to_date(TIME_UTC,"Y-m-d"));  //今天开始
    $t_end_time = to_timespan(to_date(TIME_UTC,"Y-m-d"))+ (24*3600 - 1);  //今天结束
    $y_begin_time = $t_begin_time - (24*3600); //昨天开始
    $y_end_time = $t_end_time - (24*3600);  //昨天结束

    $point = intval(app_conf("USER_ACTIVE_POINT"));
    $score = intval(app_conf("USER_ACTIVE_SCORE"));
    $money = doubleval(app_conf("USER_ACTIVE_MONEY"));
    $point_max = intval(app_conf("USER_ACTIVE_POINT_MAX"));
    $score_max = intval(app_conf("USER_ACTIVE_SCORE_MAX"));
    $money_max = doubleval(app_conf("USER_ACTIVE_MONEY_MAX"));

    $sum_money = doubleval($GLOBALS['db']->getOne("select sum(money) from ".DB_PREFIX."user_active_log where user_id = ".$user_id." and create_time between ".$t_begin_time." and ".$t_end_time));
    $sum_score = intval($GLOBALS['db']->getOne("select sum(score) from ".DB_PREFIX."user_active_log where user_id = ".$user_id." and create_time between ".$t_begin_time." and ".$t_end_time));
    $sum_point = intval($GLOBALS['db']->getOne("select sum(point) from ".DB_PREFIX."user_active_log where user_id = ".$user_id." and create_time between ".$t_begin_time." and ".$t_end_time));

    if($sum_money>=$money_max)$money = 0;
    if($sum_score>=$score_max)$score = 0;
    if($sum_point>=$point_max)$point = 0;

    if($money>0||$score>0||$point>0)
    {
        require_once  APP_ROOT_PATH."system/libs/user.php";
        modify_account(array("money"=>$money,"score"=>$score,"point"=>$point),$user_id,$log);
        $data['user_id'] = $user_id;
        $data['create_time'] = TIME_UTC;
        $data['money'] = $money;
        $data['score'] = $score;
        $data['point'] = $point;
        $GLOBALS['db']->autoExecute(DB_PREFIX."user_active_log",$data);
    }
}

/**
 * 组装借款搜索条件
 */
function build_deal_filter_condition($param,$is_store=false)
{
    $cate_id = intval($param['cid']);
    $deal_type_id = intval($param['tid']);
    $city_id = intval($GLOBALS['deal_city']['id']);
    if($is_store){
        $deal_type = intval($param['deal_type']);
        $condition = " and deal_type = $deal_type ";
    }
    else{
        $condition="";
    }
    if($city_id>0)
    {
        $ids = load_auto_cache("deal_city_belone_ids",array("city_id"=>$city_id));
        if($ids)
            $condition .= " and city_id in (".implode(",",$ids).")";
    }

    if($cate_id>0)
    {
        $cate_name = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."deal_cate where id = ".$cate_id);
        $cate_name_unicode = str_to_unicode_string($cate_name);

        if($deal_type_id>0)
        {
            $deal_type_name = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."deal_cate_type where id = ".$deal_type_id);
            $deal_type_name_unicode = str_to_unicode_string($deal_type_name);
            $condition .= " and (match(deal_cate_match) against('+".$cate_name_unicode." +".$deal_type_name_unicode."' IN BOOLEAN MODE)) ";
        }
        else
        {
            $condition .= " and (match(deal_cate_match) against('".$cate_name_unicode."' IN BOOLEAN MODE)) ";
        }
    }

    return $condition;
}

function is_animated_gif($filename){
    $fp=fopen($filename, 'rb');
    $filecontent=fread($fp, filesize($filename));
    fclose($fp);
    return strpos($filecontent,chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0')===FALSE?0:1;
}

function update_sys_config()
{
    error_reporting(0);
    //定义DB
    require_once APP_ROOT_PATH."system/db/db.php";
    $dbcfg = require_once APP_ROOT_PATH."public/db_config.php";

    if(!defined("SHOW_LOG"))
        define("SHOW_LOG",0);

    if(!file_exists(APP_ROOT_PATH.'public/runtime/app/db_caches/'))
        mkdir(APP_ROOT_PATH.'public/runtime/app/db_caches/',0777);
    $pconnect = false;
    $sys_db = new mysql_db($dbcfg['DB_HOST'].":".$dbcfg['DB_PORT'], $dbcfg['DB_USER'],$dbcfg['DB_PWD'],$dbcfg['DB_NAME'],'utf8',$pconnect);
    //end 定义DB

    $sys_configs = $sys_db->getAll("select * from ".$dbcfg['DB_PREFIX']."conf");
    $sys_config =array();
    foreach($sys_configs as $k=>$v){
        $sys_config[$v['name']]=$v['value'];
    }

    $config = array();

    $config = array_merge($config,$sys_config);

    //加载系统信息
    if(file_exists(APP_ROOT_PATH.'public/version.php'))
    {
        $version	=	require_once APP_ROOT_PATH."public/version.php";
        $config = array_merge($config,$version);
    }

    //加载时区信息
    if(file_exists(APP_ROOT_PATH.'public/timezone_config.php'))
    {
        $timezone	=	require_once APP_ROOT_PATH."public/timezone_config.php";
        $config = array_merge($config,$timezone);
    }

    // 加载数据库中的配置与数据库配置
    if(file_exists(APP_ROOT_PATH.'public/db_config.php'))
    {
        $config = array_merge($config,$dbcfg);
    }

    $config_str = "<?php\n";
    $config_str .= "return array(\n";
    foreach($config as $k=>$v)
    {
        $config_str.="'".$k."'=>'".addslashes($v)."',\n";
    }
    $config_str.=");\n ?>";

    $filename = APP_ROOT_PATH."public/sys_config.php";
    if($handle = fopen($filename, 'w')){
        fwrite($handle, $config_str);
        fclose($handle);
    }


    return $config;
}

/**
 * 等额本息还款计算方式
 * $money 贷款金额
 * $rate 月利率
 * $remoth 还几个月
 * 返回  每月还款额
 */
function pl_it_formula($money,$rate,$remoth){
    if((pow(1+$rate,$remoth)-1) > 0)
        return $money * ($rate*pow(1+$rate,$remoth)/(pow(1+$rate,$remoth)-1));
    else
        return 0;
}

/**
 * 按月还款计算方式
 * $total_money 贷款金额
 * $rate 年利率
 * 返回月应该还多少利息
 */
function av_it_formula($total_money,$rate){
    return $total_money * $rate;
}

/**
 * 获取该期剩余本金
 * int $Idx  第几期
 * int $all_idx 总的是几期
 * floatval $amount_money 总的借款多少
 * floatval $month_repay_money 月还本息
 * floatval $rate 费率
 */
function get_benjin($idx,$all_idx,$amount_money,$month_repay_money,$rate){
    //计算剩多少本金
    $benjin = $amount_money;
    for($i=1;$i<$idx+1;$i++){
        $benjin = $benjin - ($month_repay_money - $benjin*$rate/12/100);
    }
    return $benjin;
}
/**
 * 获取该期本金
 * int $Idx  第几期
 * floatval $amount_money 总的借款多少
 * floatval $month_repay_money 月还本息
 * floatval $rate 费率
 */
function get_self_money($idx,$amount_money,$month_repay_money,$rate){
    return $month_repay_money - get_benjin($idx,$idx,$amount_money,$month_repay_money,$rate)*$rate/12/100;
}

function getXmlNodeValue($xmlStr ,$nodeName){
    preg_match_all( "/\<".$nodeName."\>(.*?)\<\/".$nodeName."\>/s", $xmlStr, $nodeValue );
    return $nodeValue[1][0];
}

/**
 * 满标放款
 * $type 0 普通 1代表 第三方
 * $is_loan 0 不返款， 1 返款
 */
function do_loans($id,$repay_start_time,$type = 0){
    $return = array("status"=>0,"info"=>"");
    if($id==0){
        $return['info'] = "放款失败，借款不存在";
        return $return;
    }
    require_once(APP_ROOT_PATH."app/Lib/deal.php");

    $deal_info = get_deal($id);

    if(!$deal_info){
        $return['info'] = "放款失败，借款不存在";
        return $return;
    }
    if(!in_array($deal_info['deal_status'],array(2,4,5))){
        $return['info'] = "放款失败，借款不是满标状态";
        return $return;
    }
    if($type==0)
        $loan_data['repay_start_time'] = $repay_start_time==''?0:to_timespan(to_date(to_timespan($repay_start_time),"Y-m-d"),"Y-m-d");
    else
        $loan_data['repay_start_time'] = $repay_start_time;

    if($loan_data['repay_start_time']==0){
        $return['info'] = "放款失败，时间没选择";
        return $return;
    }

    if($type==0 && $deal_info['ips_bill_no']!=""){
        $class_name = getCollName();
        if($class_name == "Baofoo"){
            list($usec, $sec) = explode(" ", microtime());
            $microtime = ((int)($usec * 1000) + (float)$sec * 1000);
            if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."baofoo_business WHERE action_type=2 AND cus_id=".$id." AND ".$microtime." - req_time < 30000*60 ") >0){
                $return['status'] = 3;
                $return['info'] = "在半个小时内，有过满标操作，是否继续？";
            }
            else{
                $return['status'] = 2;
                $return['info'] = "";
            }
        }
        else{
            $return['status'] = 2;
            $return['info'] = "";
        }
        $return['jump'] = APP_ROOT."/index.php?ctl=collocation&act=Transfer&pTransferType=1&deal_id=".$id."&ref_data=".$loan_data['repay_start_time'];
        return $return;
    }

    if($loan_data['repay_start_time'] > 0){
        $deal_info['next_repay_time'] = $loan_data['next_repay_time'] = next_replay_month($loan_data['repay_start_time']);
    }
    $deal_info['deal_status'] = $loan_data['deal_status'] = 4;
    $deal_info['is_has_loans'] = $loan_data['is_has_loans'] = 1;
    $loan_data['repay_start_date'] = to_date($loan_data['repay_start_time'],"Y-m-d");

    //放款的时候设置成无效
    $loan_data['is_effect'] = 0;

    //放款给用户
    $GLOBALS['db']->autoExecute(DB_PREFIX."deal",$loan_data,"UPDATE","id=".$id." AND is_has_loans=0 ");

    $deal_info['repay_start_time'] = $loan_data['repay_start_time'];

    if($GLOBALS['db']->affected_rows() > 0){
        format_deal_item($deal_info);
        require_once APP_ROOT_PATH."system/libs/user.php";
        if($type == 0){
            modify_account(array("money"=>$deal_info['borrow_amount']),$deal_info['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],招标成功",3);
            //扣除服务费
            $services_fee = $deal_info['borrow_amount']*floatval(trim($deal_info['services_fee']))/100;
            modify_account(array("money"=>-$services_fee),$deal_info['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],服务费",14);

        }

        //积分
        if($deal_info['score']!=0)
            modify_account(array("score"=>$deal_info['score']),$deal_info['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],招标成功",3);
        $load_list = $GLOBALS['db']->getAll("SELECT id,user_id,`money`,`is_old_loan`,`rebate_money`,`bid_score`,`is_winning`,`income_type`,`income_value`,`ecv_id`,`learn_money` FROM ".DB_PREFIX."deal_load where deal_id=".$id." and is_rebate = 0 ");
        foreach($load_list as $lk=>$lv){
            //扣除冻结资金
            if($type == 0){
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_has_loans =1 WHERE id=".$lv['id']." AND is_has_loans = 0 AND user_id=".$lv['user_id']);
                if($GLOBALS['db']->affected_rows()){
                    if($lv['is_old_loan']==0){
                        $ecv_money = 0;
                        if($lv['ecv_id'] > 0){
                            $ecv_money = $GLOBALS['db']->getOne("SELECT `money` FROM ".DB_PREFIX."ecv WHERE id=".$lv['ecv_id']);
                        }
                        if(($lv['money']- $lv['learn_money'])-$ecv_money > 0)
                            modify_account(array("lock_money"=>-($lv['money']-$ecv_money- $lv['learn_money'])),$lv['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],投标成功",2);
                    }
                }
            }

            //管理员提成
            pay_manage_referrals($deal_info,$lv);

            //返利给用户
            if(floatval($lv["rebate_money"])!=0 || intval($lv["bid_score"])!=0){
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_rebate =1 WHERE id=".$lv['id']." AND is_rebate = 0 AND user_id=".$lv['user_id']);
                if($GLOBALS['db']->affected_rows()){
                    //返利
                    if(floatval($lv["rebate_money"])!=0)
                        modify_account(array("money"=>$lv['rebate_money']),$lv['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],投资返利",24);
                    //积分
                    if(intval($lv["bid_score"])!=0)
                        modify_account(array("score"=>$lv['bid_score']),$lv['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],投资返积分",2);



                    //VIP奖励
                    if(((int)$lv['income_type']==1 || (int)$lv['income_type']==2 || (int)$lv['income_type']==3 || (int)$lv['income_type']==4) && $lv['is_winning']==1){

                        $user_msg_conf = get_user_msg_conf($lv['user_id']);
                        //发放奖励
                        if($lv['income_type']==1){
                            //红包记录 增加用户金额与不可提现金额
                            $red_envelope_date['user_id'] = $lv['user_id'];
                            $red_envelope_date['deal_id'] = $id;
                            $red_envelope_date['load_id'] = $lv['id'];
                            $red_envelope_date['reward_name'] = "投标收益奖励";
                            $red_envelope_date['gift_type'] = 1;
                            $redmoney= $GLOBALS['db']->getOne("SELECT money FROM ".DB_PREFIX."vip_red_envelope WHERE id='".(int)$lv['income_value']."'");
                            $red_envelope_date['gift_value']=$redmoney;
                            $red_envelope_date['status'] = 1;
                            $red_envelope_date['generation_date'] = to_date(TIME_UTC,"Y-m-d");
                            $red_envelope_date['release_date'] = to_date(TIME_UTC,"Y-m-d");

                            $is_send_mail = $user_msg_conf['mail_redenvelope'];
                            $is_send_sms = $user_msg_conf['sms_redenvelope'];
                            $TPL_MAIL_NAME = "TPL_MAIL_RED_ENVELOPE";

                            if(app_conf("SMS_RED_ENVELOPE")==1){
                                $TPL_SMS_NAME = "TPL_SMS_RED_ENVELOPE";
                            }else{
                                $TPL_SMS_NAME = "";
                            }

                            $gift_value = $redmoney;

                            if($redmoney!=0&&$redmoney!=""){
                                $GLOBALS['db']->autoExecute(DB_PREFIX."gift_record",$red_envelope_date); //插入
                                modify_account(array('money'=>$redmoney,'nmc_amount'=>$redmoney),$lv['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],的投标收益奖励  红包现金",28);
                            }

                        }elseif($lv['income_type']==2){
                            //收益率
                            $rate_date['user_id'] = $lv['user_id'];
                            $rate_date['deal_id'] = $id;
                            $rate_date['load_id'] = $lv['id'];
                            $rate_date['reward_name'] = "投标收益奖励";
                            $rate_date['gift_type'] = 2;
                            $loadinfo = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_load_repay WHERE load_id='".$lv['id']."'");
                            $interest_money = $loadinfo['repay_money']-$loadinfo['self_money'];
                            $gift_value = $interest_money * (float)$lv['income_value'] * 0.01;
                            $rate_date['reward_money']=$gift_value;
                            $rate_date['gift_value']=$lv['income_value'];
                            $rate_date['status'] = 1;
                            $rate_date['generation_date'] = to_date(TIME_UTC,"Y-m-d");
                            $rate_date['release_date'] = to_date(TIME_UTC,"Y-m-d");
                            $GLOBALS['db']->autoExecute(DB_PREFIX."gift_record",$rate_date); //插入

                        }elseif($lv['income_type']==3){
                            //积分
                            $score=(int)$lv['income_value'];
                            $score_date['user_id'] = $lv['user_id'];
                            $score_date['deal_id'] = $id;
                            $score_date['load_id'] = $lv['id'];
                            $score_date['reward_name'] = "投标收益奖励";
                            $score_date['gift_type'] = 3;
                            $score_date['gift_value']=(int)$lv['income_value'];
                            $score_date['status'] = 1;
                            $score_date['generation_date'] = to_date(TIME_UTC,"Y-m-d");
                            $score_date['release_date'] = to_date(TIME_UTC,"Y-m-d");
                            $GLOBALS['db']->autoExecute(DB_PREFIX."gift_record",$score_date); //插入

                            $is_send_mail = $user_msg_conf['mail_integral'];
                            $is_send_sms = $user_msg_conf['sms_integral'];
                            $TPL_MAIL_NAME = "TPL_MAIL_INTEGRAL";
                            if(app_conf("SMS_INTEGRAL")==1){
                                $TPL_SMS_NAME = "TPL_SMS_INTEGRAL";
                            }else{
                                $TPL_SMS_NAME = "";
                            }
                            $gift_value = (int)$lv['income_value'];

                            if($score!=0){
                                modify_account(array("score"=>$score),$lv['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],的投标收益奖励 积分",28);
                            }

                        }elseif($lv['income_type']==4){
                            //礼品记录
                            $gift_date['user_id'] = $lv['user_id'];
                            $gift_date['deal_id'] = $id;
                            $gift_date['load_id'] = $lv['id'];
                            $gift_date['reward_name'] = "投标收益奖励";
                            $gift_date['gift_type'] = 4;
                            $gift_date['gift_value']=(int)$lv['income_value'];
                            $gift_date['status'] = 1;
                            $gift_date['generation_date'] = to_date(TIME_UTC,"Y-m-d");
                            $gift_date['release_date'] = to_date(TIME_UTC,"Y-m-d");
                            $GLOBALS['db']->autoExecute(DB_PREFIX."gift_record",$gift_date); //插入

                            $is_send_mail = $user_msg_conf['mail_gift'];
                            $is_send_sms = $user_msg_conf['sms_gift'];
                            $TPL_MAIL_NAME = "TPL_MAIL_GIFT";
                            if(app_conf("SMS_GIFT")==1){
                                $TPL_SMS_NAME = "TPL_SMS_GIFT";
                            }else{
                                $TPL_SMS_NAME = "";
                            }

                            $gift_value = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."vip_gift where id = ".$gift_date['gift_value']);


                        }

                        $user_info = get_user_info("*","id = ".$lv['user_id']);
                        $deal_name = $deal_info['name'];


                        //邮件
                        if($is_send_mail == 1 && app_conf("MAIL_ON")==1)
                        {
                            $tmpl = $GLOBALS['db']->getRowCached("select * from ".DB_PREFIX."msg_template where name = '".$TPL_MAIL_NAME."'");
                            $tmpl_content = $tmpl['content'];


                            $notice['user_name'] = $user_info['user_name'];
                            $notice['deal_name'] = $deal_name;
                            $notice['release_date'] = to_date(TIME_UTC,"Y-m-d");
                            $notice['site_name'] = app_conf("SHOP_TITLE");
                            $notice['gift_value'] = $gift_value;

                            $GLOBALS['tmpl']->assign("notice",$notice);

                            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                            $msg_data['dest'] = $user_info['email'];
                            $msg_data['send_type'] = 1;
                            $msg_data['title'] = "投标奖励邮件通知";
                            $msg_data['content'] = addslashes($msg);
                            $msg_data['send_time'] = 0;
                            $msg_data['is_send'] = 0;
                            $msg_data['create_time'] = TIME_UTC;
                            $msg_data['user_id'] = $user_info['id'];
                            $msg_data['is_html'] = $tmpl['is_html'];
                            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
                        }

                        //短信
                        if($is_send_sms == 1 && app_conf("SMS_ON")==1)
                        {
                            $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = '".$TPL_SMS_NAME."'");
                            $tmpl_content = $tmpl['content'];

                            $notice['user_name'] = $user_info['user_name'];
                            $notice['deal_name'] = $deal_name;
                            $notice['release_date'] = to_date(TIME_UTC,"Y-m-d");
                            $notice['site_name'] = app_conf("SHOP_TITLE");
                            $notice['gift_value'] = $gift_value;

                            $GLOBALS['tmpl']->assign("notice",$notice);

                            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);

                            $msg_data['dest'] = $user_info['mobile'];
                            $msg_data['send_type'] = 0;
                            $msg_data['title'] = "投标奖励短信通知";
                            $msg_data['content'] = addslashes($msg);;
                            $msg_data['send_time'] = 0;
                            $msg_data['is_send'] = 0;
                            $msg_data['create_time'] = TIME_UTC;
                            $msg_data['user_id'] = $user_info['id'];
                            $msg_data['is_html'] = $tmpl['is_html'];
                            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
                        }

                    }
                }
            }




            //投标人 VIP升级
            $tuser_id=$lv['user_id'];
            $ttype = 1;
            $ttype_info = 2;
            $tresultdate = syn_user_vip($tuser_id,$ttype,$ttype_info);


        }

        //VIP升级 -借款
        $type = 1;
        $type_info = 1;
        $resultdate = syn_user_vip($deal_info['user_id'],$type,$type_info);

        //$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",array("is_has_loans"=>1),"UPDATE","deal_id=".$id);


        make_repay_plan($deal_info);

        //放完款的时候重新设置成有效
        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal SET is_effect=1 WHERE id=".$id);

        //发借款成功邮件
        send_deal_success_mail_sms($id,$deal_info);

        if(app_conf("WEIXIN_MSG")==1){
            if(!$user_info)
                $user_info = get_user_info("*","id = ".$deal_info['user_id']);
            if($user_info['wx_openid']){
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM200685723' ");
                $today = to_date(TIME_UTC,"Y-m-d");
                $weixin_data['first'] = array('value'=>$user_info['user_name'].'的借款','color'=>'#173177');
                $weixin_data['keyword1']=array('value'=>$deal_info['name'],'color'=>'#173177');
                $weixin_data['keyword2']=array('value'=>'满标通知','color'=>'#173177');
                weixin_tmpl_send($tmpl['template_id'],$user_info['id'],$weixin_data);
            }
        }

        //发借款成功站内信
        send_deal_success_site_sms($id,$deal_info);

        //借款协议范本
        send_deal_contract_email($id,$deal_info,$deal_info['user_id']);

        $return['status'] = 1;
        $return['info'] = "放款成功";
        return $return;
    }
    else{
        $return['info'] = "放款失败";
        return $return;
    }
}

/**
 * 流标还返
 * $id deal_id
 * $type 0 普通返回，  1资金托管
 */

function do_received($id,$type = 0,$bad_msg = ""){

    $return = array("status"=>0,"info"=>"");
    if($id==0){
        $return['info'] = "返还失败，借款不存在";
        return $return;
    }
    require_once(APP_ROOT_PATH."app/Lib/deal.php");
    syn_deal_status($id);
    $deal_info = get_deal($id,0);

    if(!$deal_info){
        $return['info'] = "返还失败，借款不存在";
        return $return;
    }
    if(intval($deal_info['deal_status'])>=4){
        $return['info'] = "返还失败，借款状态为还款状态";
        return $return;
    }

    if($type==0 && $deal_info['ips_bill_no']!=""){
        $class_name = getCollName();
        if($class_name == "Baofoo"){
            list($usec, $sec) = explode(" ", microtime());
            $microtime = ((int)($usec * 1000) + (float)$sec * 1000);
            if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."baofoo_business WHERE action_type=3 AND cus_id=".$id." AND ".$microtime." - req_time < 30000*60 ") >0){
                $return['status'] = 3;
                $return['info'] = "在半个小时内，有过流标操作，是否继续？";
            }
            else{
                $return['status'] = 2;
                $return['info'] = "";
            }
        }
        else{
            $return['status'] = 2;
            $return['info'] = "";
        }
        $return['jump'] = "http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterSubject&pOperationType=2&status=2&status_msg=$bad_msg&deal_id=".$id;
        return $return;
    }

    if($type == 0){
        //流标时返还
        require_once APP_ROOT_PATH."system/libs/user.php";
        $r_load_list = $GLOBALS['db']->getAll("SELECT id,user_id,money,is_old_loan,ecv_id,learn_id,learn_money,interestrate_id FROM ".DB_PREFIX."deal_load WHERE is_repay=0 AND deal_id=$id");
        foreach($r_load_list as $k=>$v){
            $ecv_money = 0;
            if($v['ecv_id'] > 0){
                $ecv_money = $GLOBALS['db']->getOne("SELECT `money` FROM ".DB_PREFIX."ecv WHERE id=".$v['ecv_id']);
            }

            if(($v['money']- $v['learn_money'])-$ecv_money > 0){
                if($v['is_old_loan']==0)
                    modify_account(array("money"=>($v['money']-$ecv_money - $v['learn_money']),"lock_money"=>-($v['money']-$ecv_money- $v['learn_money'])),$v['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],流标返还",19);
                else
                    modify_account(array("money"=>($v['money']-$ecv_money - $v['learn_money'])),$v['user_id'],"[<a href='".$deal_info['url']."' target='_blank'>".$deal_info['name']."</a>],流标返还",19);
            }

            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_repay=1 WHERE id=".$v['id']);

            if($v['ecv_id'] > 0)
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv SET use_count=use_count - 1 WHERE id=".$v['ecv_id']);

            if($v['interestrate_id'] > 0)
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate SET use_count=use_count - 1 WHERE id=".$v['interestrate_id']);


            if($v['learn_id'] > 0)
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."learn_send_list SET is_use=0 WHERE id=".$v['learn_id']);
        }
    }
    else{
        $r_load_list = $GLOBALS['db']->getAll("SELECT id,user_id,money,is_old_loan,ecv_id,interestrate_id FROM ".DB_PREFIX."deal_load WHERE is_repay=0 AND deal_id=$id");
        foreach($r_load_list as $k=>$v){
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET is_repay=1 WHERE id=".$v['id']);
            if($v['ecv_id'] > 0)
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv SET use_count=use_count - 1 WHERE id=".$v['ecv_id']);
            if($v['interestrate_id'] > 0)
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate SET use_count=use_count - 1 WHERE id=".$v['interestrate_id']);
        }
    }

    if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_load WHERE is_repay=0 AND deal_id=$id") > 0){
        $bad_data['bad_msg'] = $bad_msg;
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal",$bad_data,"UPDATE","id=".$id);
        $return['status'] = 1;
        $return['info'] = "部分返还";
        return $return;
    }
    else{
        $bad_data['is_has_received'] = 1;
        $bad_data['bad_msg'] = $bad_msg;
        $bad_data['bad_time'] = TIME_UTC;
        $bad_data['bad_date'] = to_date(TIME_UTC,"Y-m-d");
        $bad_data['deal_status'] = 3;
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal",$bad_data,"UPDATE","id=".$id);
        $return['status'] = 1;
        $return['info'] = "返还成功";
        return $return;
    }
}

function get_site_email($user_id){
    $domian_attr =  explode(".",str_replace(array("https://","http://","/"),"",SITE_DOMAIN));
    $len = count($domian_attr);

    if($len==1)
        return $user_id."@".$domian_attr[$len-1].".com";
    else
        return $user_id."@".$domian_attr[$len-2].".".$domian_attr[$len-1];

}


function isMobile() {
    /*// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
	if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
		return true;
	}
	//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
	if (isset ($_SERVER['HTTP_VIA'])) {
		//找不到为flase,否则为true
		return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
	}
	//判断手机发送的客户端标志,兼容性有待提高
	if (isset ($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array (
				'nokia',
				'sony',
				'ericsson',
				'mot',
				'samsung',
				'htc',
				'sgh',
				'lg',
				'sharp',
				'sie-',
				'philips',
				'panasonic',
				'alcatel',
				'lenovo',
				'iphone',
				'ipod',
				'blackberry',
				'meizu',
				'android',
				'netfront',
				'symbian',
				'ucweb',
				'windowsce',
				'palm',
				'operamini',
				'operamobi',
				'openwave',
				'nexusone',
				'cldc',
				'midp',
				'wap',
				'mobile'
		);
		// 从HTTP_USER_AGENT中查找手机浏览器的关键字
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	//协议法，因为有可能不准确，放到最后判断
	if (isset ($_SERVER['HTTP_ACCEPT'])) {
		// 如果只支持wml并且不支持html那一定是移动设备
		// 如果支持wml和html但是wml在html之前则是移动设备
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}*/

    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    $mobile_browser = '0';
    if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        $mobile_browser++;
    if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
        $mobile_browser++;
    if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
        $mobile_browser++;
    if(isset($_SERVER['HTTP_PROFILE']))
        $mobile_browser++;
    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
    $mobile_agents = array(
        'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
        'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
        'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
        'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
        'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
        'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
        'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
        'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
        'wapr','webc','winw','winw','xda','xda-'
    );
    if(in_array($mobile_ua, $mobile_agents))
        $mobile_browser++;
    if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
        $mobile_browser++;
    // Pre-final check to reset everything if the user is on Windows
    if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
        $mobile_browser=0;
    // But WP7 is also Windows, with a slightly different characteristic
    if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
        $mobile_browser++;
    if($mobile_browser>0)
        return true;
    else
        return false;
}


//给字符串添加引号
function str_quot($str,$separator=","){
    //echo $str."<br>";
    $str_arr = explode($separator,$str);
    //print_r($str_arr); exit;
    $str_new = "";
    foreach ($str_arr AS $key => $val){
        if ($str_new == ""){
            $str_new = "'".addslashes($val)."'";
        }else{
            $str_new .= ",'".addslashes($val)."'";
        }
    }

    return $str_new;
}

function date_in($start_date,$end_date,$add_quotation = true){
    $sysc_start_time = to_timespan(to_date(to_timespan($start_date),'Y-m-d'));
    $sysc_end_time = to_timespan(to_date(to_timespan($end_date),'Y-m-d'));
    if ($sysc_end_time == 0)
        $sysc_end_time = $sysc_start_time;

    if ($sysc_start_time == 0)
        $sysc_start_time = $sysc_end_time;

    $str_in = '';
    for($s_date = $sysc_start_time; $s_date <= $sysc_end_time; $s_date += 86400){
        if ($add_quotation){
            if ($str_in == ""){
                $str_in = "'".to_date($s_date,'Y-m-d')."'";
            }else{
                $str_in .= ",'".to_date($s_date,'Y-m-d')."'";
            }
        }else{
            if ($str_in == ""){
                $str_in = to_date($s_date,'Y-m-d');
            }else{
                $str_in .= ",".to_date($s_date,'Y-m-d');
            }
        }
    }
    return $str_in;
}

//日期加减
function dec_date($date,$dec){
    //$sysc_start_time = to_timespan(to_date(to_timespan($date),'Y-m-d')) - $dec * 86400;

    return to_date(to_timespan($date)  - $dec * 86400,'Y-m-d');
}

/**
 * 账单操作日志
 */
function repay_log($id,$msg,$user_id,$adm_id){
    $data['repay_id'] = $id;
    $data['log'] = $msg;
    $data['user_id'] = intval($user_id);
    $data['adm_id'] = intval($adm_id);
    $data['create_time'] = TIME_UTC;

    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay_log",$data);
    if($GLOBALS['db']->insert_id() > 0){
        return true;
    }
    else{
        return false;
    }
}

function hideMobile($mobile){
    if($mobile!="")
        return preg_replace('#(\d{3})\d{5}(\d{3})#', '${1}*****${2}',$mobile);
    else
        return "";
}

function hideIdCard($idcard){
    if($idcard!="")
        return preg_replace('#(\d{14})(\d{4}|(\w+))#', '${1}****',$idcard);
    else
        return "";

}
function hideEmail($email){
    if($email!="")
        return preg_replace('#(\w{2})\w+\@+#', '${1}****@${3}', $email);
    else
        return "";
}


function FW_DESPWD($pwd){

    $pwd = unescape(base64_decode($pwd));
    $pwd = substr($pwd,strlen(LOGIN_DES_KEY()."方维"),strlen($pwd));
    $pwd = substr($pwd,0,strlen($pwd) - strlen("软件"));
    return $pwd;
}

function  unescape($str){
    $str = rawurldecode ($str);
    preg_match_all ( "/%u.{4}|&#x.{4};|&#\d+;|.+/U", $str, $r );
    $ar = $r [0];
    foreach ( $ar as $k => $v ) {
        if (substr ( $v, 0, 2 ) == "%u")
            $ar [$k] = iconv ( "UCS-2", "UTF-8", pack ( "H4", substr ( $v, - 4 ) ) );
        elseif (substr ( $v, 0, 3 ) == "&#x")
            $ar [$k] = iconv ( "UCS-2", "UTF-8", pack ( "H4", substr ( $v, 3, - 1 ) ) );
        elseif (substr ( $v, 0, 2 ) == "&#") {
            $ar [$k] = iconv ( "UCS-2", "UTF-8", pack ( "n", substr ( $v, 2, - 1 ) ) );
        }
    }
    return join ( "", $ar );
}

function LOGIN_DES_KEY(){

    if(!es_session::is_set("DES_KEY")){
        require_once APP_ROOT_PATH."system/utils/es_string.php";
        es_session::set("DES_KEY",es_string::rand_string(50));
    }
    return es_session::get("DES_KEY");
}

function HASH_KEY(){
    if(!es_session::is_set("HASH_KEY")){
        require_once APP_ROOT_PATH."system/utils/es_string.php";
        es_session::set("HASH_KEY",es_string::rand_string(50));
    }
    return es_session::get("HASH_KEY");
}

function check_hash_key(){
    /*if(strim($_REQUEST['fhash'])!="" && md5(HASH_KEY())==md5($_REQUEST['fhash'])){
		return true;
	}
	else
		return false;
	 * */
    return true;
}


///$type   invest:投资者,borrow:借款者
function get_rebate_fee($user_id,$type)
{
    $return['rebate'] = 0;
    $return['pid'] =0;
    if($user_id)
    {
        $return['pid'] = $GLOBALS['db']->getRow("SELECT p.id FROM ".DB_PREFIX."user u left join ".DB_PREFIX."user as p on p.id=u.pid WHERE u.id = ".$user_id." and p.user_type=3 ",false) ;
        if(intval($return['pid']) > 0)
        {
            if($type == 'invest')
            {
                $return['rebate'] = (float)app_conf('INVESTORS_COMMISSION_RATIO') ;
            }
            else if($type == 'borrow')
            {
                $return['rebate'] = (float)app_conf('BORROWER_COMMISSION_RATIO') ;
            }
        }
    }
    return $return;
}

///$type   invest:投资者,borrow:借款者
function reback_rebate_money($user_id,$money,$type,$memo){

    $pid = $GLOBALS['db']->getOne("select pid from ".DB_PREFIX."user where id = ".$user_id);
    if($pid == 0)
    {
        return;
    }
    require_once APP_ROOT_PATH."system/libs/user.php";
    modify_account(array("money"=>$money),$pid,$memo,23);

}

//费用信息
function get_user_load_fee($user_id,$deal_id=0,$deal_info = array()){
    if(!$deal_info && $deal_id > 0){
        $deal_info = get_deal($deal_id);
    }
    if(intval($user_id)==0){
        return false;
    }

    $user_info = $GLOBALS['db']->getRow("select vip_id,level_id from ".DB_PREFIX."user where id= ".$user_id." ");
    $type_info = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_loan_type WHERE id=".$deal_info['type_id']);

    if($type_info['costsetting'] && $user_info['vip_id']>0){
        $vo_list = explode("\n",$type_info['costsetting']);
        foreach($vo_list as $k=>$v){
            $vo_list[$k] = explode("|",$v);
            if($vo_list[$k]['0'] == $user_info['vip_id']){
                if($vo_list[$k]['1']>0 || $vo_list[$k]['2']>0 || $vo_list[$k]['3']>0 || $vo_list[$k]['4']>0 || $vo_list[$k]['5']>0 || $vo_list[$k]['6']>0 ){
                    $deal_info['services_fee'] = $vo_list[$k]['1'];
                    $deal_info['manage_fee'] = $vo_list[$k]['2'];
                    $deal_info['user_loan_manage_fee'] = $vo_list[$k]['3'];
                    $deal_info['user_loan_interest_manage_fee'] = $vo_list[$k]['4'];
                    $deal_info['user_bid_rebate'] = $vo_list[$k]['5'];
                    $deal_info['user_bid_score_fee'] = $vo_list[$k]['6'];
                }
            }
        }
    }else{
        if($type_info['levelsetting']){
            $vol_list = explode("\n",$type_info['levelsetting']);
            foreach($vol_list as $kl=>$vl){
                $vol_list[$kl] = explode("|",$vl);
                if($vol_list[$kl]['0'] == $user_info['level_id']){
                    if($vol_list[$kl]['1']>0 || $vol_list[$kl]['2']>0 || $vol_list[$kl]['3']>0 || $vol_list[$kl]['4']>0 || $vol_list[$kl]['5']>0 || $vol_list[$kl]['6']>0){
                        $deal_info['services_fee'] = $vol_list[$kl]['1'];
                        $deal_info['manage_fee'] = $vol_list[$kl]['2'];
                        $deal_info['user_loan_manage_fee'] = $vol_list[$kl]['3'];
                        $deal_info['user_loan_interest_manage_fee'] = $vol_list[$kl]['4'];
                        $deal_info['user_bid_rebate'] = $vol_list[$kl]['5'];
                        $deal_info['user_bid_score_fee'] = $vol_list[$kl]['6'];
                    }
                }
            }
        }
    }

    return $deal_info;

}

/**
 * 投标数据格式化
 */
function return_deal_load_data($data,$user_info,$deal){
    $formatdata = array();
    if(isset($data['pMerBillNo']))
        $formatdata['pMerBillNo'] = $data['pMerBillNo'];
    if(isset($data['pContractNo']))
        $formatdata['pContractNo'] = $data["pContractNo"];
    if(isset($data['pP2PBillNo']))
        $formatdata['pP2PBillNo'] = $data['pP2PBillNo'];

    $formatdata['user_id'] = $user_info['id'];
    $formatdata['user_name'] = $user_info['user_name'];
    $formatdata['deal_id'] = $data['deal_id'];
    $formatdata['money'] = $data['money'];
    $formatdata['create_time'] = TIME_UTC;
    $formatdata['create_date'] = to_date(TIME_UTC);
    $formatdata['is_auto'] = intval($data['is_auto']);
    $type_info = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_loan_type WHERE id=".$deal['type_id']);
    if($type_info['costsetting']&&$user_info['vip_id']>0){
        $vo_list = explode("\n",$type_info['costsetting']);
        foreach($vo_list as $k=>$v){
            $vo_list[$k] = explode("|",$v);
            if($vo_list[$k]['0'] == $user_info['vip_id']){
                if($vo_list[$k]['1']>0||$vo_list[$k]['2']>0||$vo_list[$k]['3']>0||$vo_list[$k]['4']>0||$vo_list[$k]['5']>0||$vo_list[$k]['6']>0){
                    $deal['user_bid_rebate']= $vo_list[$k]['5'];
                    $deal['user_bid_score_fee']= $vo_list[$k]['6'];
                }
            }
        }
    }else{
        if($type_info['levelsetting']){
            $vol_list = explode("\n",$type_info['levelsetting']);
            foreach($vol_list as $ks=>$vs){
                $vol_list[$ks] = explode("|",$vs);
                if($vol_list[$ks]['0'] == $user_info['level_id']){
                    if($vol_list[$ks]['1']>0||$vol_list[$ks]['2']>0||$vol_list[$ks]['3']>0||$vol_list[$ks]['4']>0||$vol_list[$ks]['5']>0||$vol_list[$ks]['6']>0){
                        $deal['user_bid_rebate']= $vol_list[$ks]['5'];
                        $deal['user_bid_score_fee']= $vol_list[$ks]['6'];
                    }
                }
            }
        }
    }
    $formatdata['rebate_money'] = $formatdata['money'] * floatval(trim($deal['user_bid_rebate'])) * 0.01;

    $vip_state = $user_info['vip_state'];
    $income_value = "";
    if($vip_state==1){
        $settinginfo= $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."vip_setting WHERE vip_id='".$user_info['vip_id']."' ");

        //$deal['user_bid_score_fee'] = $settinginfo['multiple'];

        $jilu=rand(1,100);
        $income_type = 0;

        if($jilu<=$settinginfo['probability']){

            //随机奖励类型
            $rand_gift = array();
            //奖励红包
            if($settinginfo['red_envelope'] !=""){
                $rand_gift[1] = $settinginfo['red_envelope'];
            }
            //奖励利率
            if($settinginfo['rate'] > 0){
                $rand_gift[2] = $settinginfo['rate'];
            }
            //奖励积分
            if($settinginfo['integral'] > 0){
                $rand_gift[3] = $settinginfo['integral'];
            }

            //奖励礼品
            if($settinginfo['gift'] !=""){
                $rand_gift[4] = $settinginfo['gift'];
            }

            if(count($rand_gift)){
                $income_type =  array_rand($rand_gift);
                $retrun_gift = $rand_gift[$income_type];
                switch(intval($income_type)){
                    case 1:
                        $ids =  explode(",",$rand_gift[1]);
                        $k= array_rand($ids);
                        $income_value = $ids[$k];
                        break;
                    case 2:
                        $income_value=$rand_gift[2];
                        break;
                    case 3:
                        $income_value=$rand_gift[3];
                        break;
                    case 4:
                        $ids =  explode(",",$rand_gift[4]);
                        $k= array_rand($ids);
                        $income_value = $ids[$k];
                        break;
                    default :
                        $income_value="";
                        break;
                }
            }
            else{
                $income_value="";
            }

        }
        $formatdata['is_winning'] = $income_value== "" ? 0 : 1;
        $formatdata['income_type'] = $income_type;
        $formatdata['income_value'] = $income_value;
    }

    $formatdata['bid_score'] = $formatdata['money'] * floatval(trim($deal['user_bid_score_fee'])) * 0.01;
    $formatdata['ecv_id'] = intval($data['ecv_id']);
    $formatdata['interestrate_id'] = intval($data['interestrate_id']);
    $formatdata['learn_id'] = intval($data['learn_id']);
    $formatdata['learn_money'] = floatval($data['learn_money']);
    $formatdata['has_auth'] = intval($data['has_auth']);

    return $formatdata;
}


/**
 * 获得当前使用的，资金管理名称
 * @return string
 */
function getCollName(){

    $rs = M('collocation')->where('is_effect = 1')->field('class_name')->find() ; //->query("select class_name from ".DB_PREFIX."collocation where is_effect = 1 limit 1");
    return $rs['class_name'] ;
    /*if(intval(app_conf("OPEN_IPS"))==1){
		return 'Ips';
	}else if(intval(app_conf("OPEN_IPS"))==2){
		return 'Yeepay';
	}else if(intval(app_conf("OPEN_IPS"))==3){
		return 'Baofoo';
	}else {
		return '';
	}*/
}
function get_ips_incharge($user_id)
{
    $type = getCollName();
    if($type=='Ips')
    {
        $GLOBALS['db'] = M();return $GLOBALS['db']->query("select sum(pTrdAmt) from ".DB_PREFIX."ips_do_dp_trade where pErrCode = 'MG00000F' and user_id = ".$user_id);
    }
    elseif($type=='Baofoo')
    {
        $GLOBALS['db'] = M();return $GLOBALS['db']->query("select sum(amount) from ".DB_PREFIX."baofoo_recharge where code = 'CSD000' and is_callback >=1 and user_id = ".$user_id);
    }
    elseif($type=='Yeepay')
    {
        $GLOBALS['db'] = M();return $GLOBALS['db']->query("select sum(amount) from ".DB_PREFIX."yeepay_recharge where code = 1 and is_callback >=1  and platformUserNo = ".$user_id);
    }
    elseif($type=='Fuioupay')
    {
        $GLOBALS['db'] = M();return $GLOBALS['db']->query("select sum(amount) from ".DB_PREFIX."fuioupay_recharge where code = '0000' and is_callback >=1  and user_id = ".$user_id);
    }
}

/**
 * VIP 升降级
 */
/**
 * VIP 升降级
 */
function syn_user_vip($user_id=0,$type=0,$type_info=0,$vip_id=0){
    $vipdata = array();
    //$type_info 1借款升级、2投标升级、3正常还款升级、4提前还款升级、5.逾期还款降级、6.代还款降级、7.坏账降级、8.VIP购买升级、9.VIP购买到期降级、10.管理员操作VIP升级、11.管理员操作VIP降级
    switch($type_info){
        case "1":
            $vipdata['causes']="借款升级";
            break;
        case "2":
            $vipdata['causes']="投标升级";
            break;
        case "3":
            $vipdata['causes']="正常还款升级";
            break;
        case "4":
            $vipdata['causes']="提前还款升级";
            break;
        case "5":
            $vipdata['causes']="逾期还款降级";
            break;
        case "6":
            $vipdata['causes']="代还款降级";
            break;
        case "7":
            $vipdata['causes']="坏账降级";
            break;
        case "8":
            $vipdata['causes']="VIP购买升级";
            break;
        case "9":
            $vipdata['causes']="VIP购买到期降级";
            break;
        case "10":
            $vipdata['causes']="管理员操作VIP升级";
            break;
        case "11":
            $vipdata['causes']="管理员操作VIP降级";
            break;
        default :
            $vipdata['causes']="";
            break;
    }
    $vipdata['user_id'] = $user_id;
    $now_time = TIME_UTC;
    $today=to_date(TIME_UTC,"Y-m-d");
    $start_time=to_date(next_replay_month(TIME_UTC,-24),"Y-m-d");
    $begin_date=to_date(next_replay_month(TIME_UTC,-3),"Y-m-d");

    $is_buy_time =  $GLOBALS['db']->getOne("select count(*) FROM ".DB_PREFIX."user WHERE vip_end_time > '$now_time' and id='$user_id' ");

    $user_info= get_user_info("*","id='$user_id' ");
    $borrow_total = $GLOBALS['db']->getOne("select sum(borrow_amount) FROM ".DB_PREFIX."deal WHERE start_date>'$start_time' and user_id='$user_id' and deal_status > 3 ");
    $overdue_total = $GLOBALS['db']->getOne("select sum(repay_money) FROM ".DB_PREFIX."deal_repay WHERE ((has_repay=1 and repay_date<true_repay_date) or (has_repay=0 and repay_date <'$today')) and user_id='$user_id' ");
    $load_total = $GLOBALS['db']->getOne("select sum(dl.money) FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON dl.deal_id=d.id WHERE dl.create_date>'$start_time' and dl.user_id='$user_id' and d.deal_status > 3  ");
    $t_u_load = $GLOBALS['db']->getRow("SELECT sum(dlr.repay_money) as load_money  FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d ON d.id=dlr.deal_id LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id=dlr.load_id WHERE d.is_effect=1 and dl.is_repay= 0 and  dlr.t_user_id = ".$user_id);
    $load_total = floatval($load_total) + floatval($t_u_load['load_money']);

    $bl_total=$borrow_total+$load_total-$overdue_total;
    $gradeinfo = $GLOBALS['db']->getRow("select * FROM ".DB_PREFIX."vip_type WHERE lower_limit<='$bl_total' and upper_limit>='$bl_total' and is_effect='1' and is_delete='0' ");
    //VIP 购买到期 或  VIP购买时 执行升降级
    if($is_buy_time == 0 || $type_info == 8 || $type_info == 10 || $type_info == 11){

        if($type==0){

        }elseif($type==1){
            //升级
            $overdue_num = $GLOBALS['db']->getOne("select count(*) FROM ".DB_PREFIX."deal_repay WHERE ((has_repay=1 and repay_date<true_repay_date and repay_date>'$begin_date') or (has_repay=0 and repay_date <'$today'))  and user_id='$user_id' ");
            $demotion_num = $GLOBALS['db']->getOne("select count(*) FROM ".DB_PREFIX."demotion_record  WHERE status=0 and user_id='$user_id' and eresume_date>'$today' ");
            $rdemotion_num = $GLOBALS['db']->getOne("select count(*) FROM ".DB_PREFIX."demotion_record  WHERE status=0 and user_id='$user_id' and eresume_date<='$today' ");
            //三个月内无逾期还款且 超过了预计降级还原期
            if($overdue_num==0 && $demotion_num==0 || ($type_info == 8 || $type_info == 10) || $type_info == 11 ){

                $vipdata['original_vip_id'] = $user_info['vip_id'];

                if($type_info == 8 || $type_info == 10){
                    $vipdata['now_vip_id'] = $vip_id;
                }else{
                    $vipdata['now_vip_id'] = $gradeinfo['id'];
                }

                $vipdata['upgrade_date'] = to_date(TIME_UTC,"Y-m-d");
                if($type_info == 8 || $type_info == 10){
                    if(($vipdata['now_vip_id']!=$user_info['vip_id'])){
                        $GLOBALS['db']->autoExecute(DB_PREFIX."vip_upgrade_record",$vipdata,"INSERT");
                    }
                }else{
                    if(($gradeinfo['id']!=$user_info['vip_id'])&&($gradeinfo['id']!=0)){
                        $GLOBALS['db']->autoExecute(DB_PREFIX."vip_upgrade_record",$vipdata,"INSERT");
                    }
                }


                $GLOBALS['db']->query("update ".DB_PREFIX."user SET vip_id='".$vipdata['now_vip_id']."',vip_state='1' WHERE id=".$user_id);

                if($rdemotion_num>0){
                    $GLOBALS['db']->query("update ".DB_PREFIX."demotion_record SET status='1',arecovery_date='$today' WHERE status=0 and user_id='$user_id' and eresume_date<='$today' ");
                }

                if($vipdata['now_vip_id']!=$user_info['vip_id']){
                    $group_arr = array(0,$user_id);
                    sort($group_arr);
                    $group_arr[] =  22;

                    $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_INS_VIP_UPGRADE'",false);
                    $tmpl_content = $tmpl['content'];

                    $original_vip = $GLOBALS['db']->getRow("select * FROM ".DB_PREFIX."vip_type WHERE id= '".$vipdata['original_vip_id']."' ");
                    $now_vip = $GLOBALS['db']->getRow("select * FROM ".DB_PREFIX."vip_type WHERE id= '".$vipdata['now_vip_id']."' ");

                    $sh_notice['original_vip_id'] = $original_vip['vip_grade'];
                    $sh_notice['now_vip_id'] = $now_vip['vip_grade'];
                    $sh_notice['causes'] = $vipdata['causes'];

                    $GLOBALS['tmpl']->assign("sh_notice",$sh_notice);
                    $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                    $msg_data['to_user_id'] = $user_id;
                    $msg_data['create_time'] = TIME_UTC;
                    $msg_data['title'] = "VIP等级升级";
                    $msg_data['content'] = addslashes($msg);
                    $msg_data['is_notice'] = 22;
                    $msg_data['group_key'] = implode("_",$group_arr);
                    $GLOBALS['db']->autoExecute(DB_PREFIX."msg_box",$msg_data);
                    $id = $GLOBALS['db']->insert_id();
                    $GLOBALS['db']->query("update ".DB_PREFIX."msg_box set group_key = '".$msg_data['group_key']."_".$id."' where id = ".$id);
                }


            }
        }elseif($type==2){

            //降级
            if($type_info == 9){
                $now_grade = $gradeinfo['id'];
            }elseif($type_info == 11){
                $now_grade = $vip_id;
            }else{
                $now_grade = $GLOBALS['db']->getOne("select id FROM ".DB_PREFIX."vip_type WHERE sort<'".$gradeinfo['sort']."' and is_effect='1' and is_delete='0' order by sort desc limit 1 ");
            }
            //if($gradeinfo['vip_grade']!="普通VIP会员"&&$user_info['vip_id']!=0 ){
            $GLOBALS['db']->query("update ".DB_PREFIX."user SET vip_id='".$now_grade."' WHERE id=".$user_id);
            //}
            $vipdata['original_vip_id'] = $user_info['vip_id'];
            $vipdata['now_vip_id'] = $now_grade;
            $vipdata['start_date'] = to_date(TIME_UTC,"Y-m-d");
            if($type_info == 9){
                $vipdata['eresume_date'] = to_date(TIME_UTC,"Y-m-d");
                $vipdata['status'] = 1;
            }else{
                $vipdata['eresume_date'] = to_date(next_replay_month(TIME_UTC,3),"Y-m-d");
                $vipdata['status'] = 0;
            }

            if($type_info == 11){
                $now_time = TIME_UTC;
                $VipBuyLog = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."vip_buy_log where user_id='$user_id' AND vip_buytime <= '$now_time' AND vip_end_time>= '$now_time'  order by id desc limit 1 ");
                $vipdata['eresume_date'] = to_date($VipBuyLog['vip_end_time'],"Y-m-d");
                $vipdata['status'] = 1;
                $GLOBALS['db']->autoExecute(DB_PREFIX."demotion_record",$vipdata,"INSERT");

            }else{
                if($demotion_num==0&&$gradeinfo['vip_grade']!="普通VIP会员"&&$user_info['vip_id']!=0 ){
                    $GLOBALS['db']->autoExecute(DB_PREFIX."demotion_record",$vipdata,"INSERT");
                }
            }

            if($gradeinfo['vip_grade']!="普通VIP会员"&&$user_info['vip_id']!=0 ){
                $group_arr = array(0,$user_id);
                sort($group_arr);
                $group_arr[] =  22;

                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_INS_VIP_DOWNGRADE'",false);
                $tmpl_content = $tmpl['content'];

                $original_vip = $GLOBALS['db']->getRow("select * FROM ".DB_PREFIX."vip_type WHERE id= '".$vipdata['original_vip_id']."' ");
                $now_vip = $GLOBALS['db']->getRow("select * FROM ".DB_PREFIX."vip_type WHERE id= '".$vipdata['now_vip_id']."' ");

                $sh_notice['original_vip_id'] = $original_vip['vip_grade'];
                $sh_notice['now_vip_id'] = $now_vip['vip_grade'];
                $sh_notice['causes'] = $vipdata['causes'];

                $GLOBALS['tmpl']->assign("sh_notice",$sh_notice);
                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['to_user_id'] = $user_id;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['title'] = "VIP等级降级";
                $msg_data['content'] = addslashes($msg);
                $msg_data['is_notice'] = 22;
                $msg_data['group_key'] = implode("_",$group_arr);
                $GLOBALS['db']->autoExecute(DB_PREFIX."msg_box",$msg_data);
                $id = $GLOBALS['db']->insert_id();
                $GLOBALS['db']->query("update ".DB_PREFIX."msg_box set group_key = '".$msg_data['group_key']."_".$id."' where id = ".$id);
            }

        }
    }

    return $vipdata;
}


function get_loantype_info($id){
    if($id == 0){
        return ;
    }
    $type_info = load_auto_cache("deal_loan_type_list",array("id"=>$id));
    return $type_info[$id];
}
function get_domain(){
    return 'http://wap.yzlicai.com';
}
function get_user_info($extField,$extWhere="",$Type="ROW")
{
    $m = M("user");
    if($extField=="*"){
        $extField = "*,
        AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name,
        AES_DECRYPT(email_encrypt,'".AES_DECRYPT_KEY."') as email ,
        AES_DECRYPT(idno_encrypt,'".AES_DECRYPT_KEY."') as idno,
        AES_DECRYPT(idno_encrypt,'".AES_DECRYPT_KEY."') as idno,
        AES_DECRYPT(money_encrypt,'".AES_DECRYPT_KEY."') as money,
        AES_DECRYPT(mobile_encrypt,'".AES_DECRYPT_KEY."') as mobile";
    }

    if(strpos(strtolower($extWhere),"where")===false){
        $extWhere = " WHERE ".$extWhere;
    }

    $result = array();
    switch(strtoupper($Type)){
        case "ROW":
            $result = $m->query("select $extField from ".DB_PREFIX."user $extWhere ");
            return $result[0];
            break;
        case "ALL":
            $result = $m->select("select $extField from ".DB_PREFIX."user $extWhere ");
            break;
        case "ONE":
            $result = $m->query("select $extField from ".DB_PREFIX."user $extWhere ");
            return $result[0];
            break;
        case "ONE_ENCRYPT":
            $result = $m->query("select $extField as a from ".DB_PREFIX."user $extWhere ");
            return $result[0]['a'];
            break;
    }

    return $result;
}

function isWeixin(){
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $is_weixin = strpos($agent, 'micromessenger') ? true : false ;
    if($is_weixin){
        return true;
    }else{
        return false;
    }
}

function url_wap($route="index",$param=array())
{
    return wap_url("index",$route,$param);
}

function  isIpAllow(){
    $iplist = strim(app_conf("SMS_SEND_IP_NOALLOW"));
    if($iplist==""){
        return true;
    }

    $iplist = str_replace("\r","",$iplist);
    $ip_arr = explode("\n",$iplist);

    if(in_array(CLIENT_IP,$ip_arr)){
        return false;
    }
    else{
        return true;
    }
}

function ofc_max($max_value)
{
    $max_value = floor($max_value);
    $begin_val = substr($max_value,0,1);
    $max_length = strlen($max_value)-1;
    $begin_val = intval($begin_val)+1;

    $multi = "1";
    for($i=0;$i<$max_length;$i++)
    {
        $multi.="0";
    }
    $multi = intval($multi);
    $max_value = $begin_val*$multi;

    if($max_value<=10)$max_value = 10;
    if($max_value>10&&$max_value<=200)$max_value = 200;

    return $max_value;
}


/**
 * 发放注册奖励
 */
function send_register_reward($user_id,$date_time="",$pid=0){
    if($user_id == 0)
        return false;
    if($date_time==""){
        $date_time = to_date(TIME_UTC);
    }
    require_once APP_ROOT_PATH."system/libs/user.php";
    $register_money = doubleval(app_conf("USER_REGISTER_MONEY"));
    $register_score = intval(app_conf("USER_REGISTER_SCORE"));
    $register_point = intval(app_conf("USER_REGISTER_POINT"));
    $register_lock_money = intval(app_conf("USER_LOCK_MONEY"));
    $register_redbag = intval(app_conf("USER_REGISTER_REDBAG"));
    if($register_money>0||$register_score>0 || $register_point > 0 || $register_lock_money>0 )
    {
        $user_get['score'] = $register_score;
        $user_get['money'] = $register_money;
        $user_get['point'] = $register_point;
        $user_get['lock_money'] = $register_lock_money;
        modify_account($user_get,intval($user_id),"在".$date_time."注册成功",18);
    }
    if($register_redbag > 0){
        modify_account(array('money'=>$register_redbag,'nmc_amount'=>$register_redbag),intval($user_id),"在".$date_time."注册成功,送红包",18);
    }

    //红包
    //获取未过期的注册红包
    //$ecv_list = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."ecv_type WHERE (begin_time= 0 or begin_time < ".TIME_UTC.") AND (end_time= 0 or end_time +24*3600-1 > ".TIME_UTC.") AND  send_type=3 ");
    $ecv_list = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."ecv_type WHERE send_type=3 ");
    if($ecv_list){
        foreach($ecv_list as $k=>$v){
            require_once APP_ROOT_PATH."system/libs/voucher.php";
            send_voucher($v['id'],$user_id,0);
        }
    }
    //加息券
    //获取未过期的注册加息券
    $ecv_list = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."interestrate_type WHERE (begin_time= 0 or begin_time < ".TIME_UTC.") AND (end_time= 0 or end_time +24*3600-1 > ".TIME_UTC.") AND  send_type=3 ");
    if($ecv_list){
        foreach($ecv_list as $k=>$v){
            require_once APP_ROOT_PATH."system/libs/voucher.php";
            send_interestrate($v['id'],$user_id,0);
        }
    }

    $now_time = to_date(TIME_UTC,'Y-m-d');
    /*
     * 邀请送体验金
     */
    if($pid >0){
        $learn_invite = $GLOBALS['db']->getOne("select sum(lsl.money) from ".DB_PREFIX."learn_send_list lsl left join ".DB_PREFIX."learn_type lt on lsl.type_id = lt.id where lt.type = 1 and lsl.is_effect = 1 and lsl.user_id ='".$pid."' ");
        $learn_type_invite = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."learn_type where type = 1 and ('".$now_time."' between begin_time and end_time) and is_effect = 1 and (max_money = 0 OR ".floatval($learn_invite)." < max_money) order by id desc limit 1 ");
        $referral_ip_limit =  $learn_type_invite['referral_ip_limit'];
        if($referral_ip_limit ==1)//ip限制
        {
            $parent_info = $GLOBALS['db']->getRow("select login_ip,user_name from ".DB_PREFIX."user where id = ".$pid);
            $referrals_data['user_name']=$parent_info['user_name'];
        }

        if($learn_type_invite){
            if(($referral_ip_limit ==1 && $parent_info['login_ip'] != CLIENT_IP) || $referral_ip_limit==0){
                $learn_invite_data['user_id'] = $pid;
                $learn_invite_data['type_id'] = $learn_type_invite['id'];
                $learn_invite_data['money'] = $learn_type_invite['money'];
                $learn_invite_data['type'] = 0;
                $learn_invite_data['begin_time'] = $now_time;
                $end_time = to_timespan($learn_invite_data['begin_time'],"Y-m-d")+$learn_type_invite['time_limit'] * 24 * 3600;
                $learn_invite_data['end_time'] = to_date($end_time,'Y-m-d');
                $learn_invite_data['is_use'] = 0;
                $learn_invite_data['is_effect'] = 1;

                $GLOBALS['db']->autoExecute(DB_PREFIX."learn_send_list",$learn_invite_data);
            }


        }
    }

    /*
     * 注册送体验金
     */
    $learn_type = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."learn_type where type = 0 and ('".$now_time."' between begin_time and end_time ) and is_effect = 1 order by id desc limit 1 ");
    if($learn_type){

        $learn_send_data['user_id'] = $user_id;
        $learn_send_data['type_id'] = $learn_type['id'];
        $learn_send_data['money'] = $learn_type['money'];
        $learn_send_data['type'] = 0;
        $learn_send_data['begin_time'] = $now_time;
        $end_time = to_timespan($learn_send_data['begin_time'],"Y-m-d")+$learn_type['time_limit'] * 24 * 3600 ;
        $learn_send_data['end_time'] = to_date($end_time,'Y-m-d');
        $learn_send_data['is_use'] = 0;
        $learn_send_data['is_effect'] = 1;
        $GLOBALS['db']->autoExecute(DB_PREFIX."learn_send_list",$learn_send_data);

    }
}

//会员信息发送
/**
 *
 * @param $title 标题
 * @param $content 内容
 * @param $from_user_id 发件人
 * @param $to_user_id 收件人
 * @param $create_time 时间
 * @param $sys_msg_id 系统消息ID
 * @param $only_send true为只发送，生成发件数据，不生成收件数据
 * @param $fav_id 相关ID
 */
function send_user_msg($title,$content,$from_user_id,$to_user_id,$create_time,$sys_msg_id=0,$only_send=false,$is_notice = false,$fav_id = 0)
{
    $group_arr = array($from_user_id,$to_user_id);
    sort($group_arr);
    if($sys_msg_id>0){
        $group_arr[] = $sys_msg_id;
    }
    if($is_notice > 0){
        $group_arr[] = $is_notice;
    }
    $msg = array();
    $msg['title'] = $title;
    $msg['content'] = addslashes($content);
    $msg['from_user_id'] = $from_user_id;
    $msg['to_user_id'] = $to_user_id;
    $msg['create_time'] = $create_time;
    $msg['system_msg_id'] = $sys_msg_id;
    $msg['type'] = 0;
    $msg['group_key'] = implode("_",$group_arr);
    $msg['is_notice'] = intval($is_notice);
    $msg['fav_id'] = intval($fav_id);
    $GLOBALS['db']->autoExecute(DB_PREFIX."msg_box",$msg);
    $id = $GLOBALS['db']->insert_id();
    if($is_notice)
        $GLOBALS['db']->query("update ".DB_PREFIX."msg_box set group_key = '".$msg['group_key']."_".$id."' where id = ".$id);
    if(!$only_send)
    {
        $msg['type'] = 1; //记录发件
        $GLOBALS['db']->autoExecute(DB_PREFIX."msg_box",$msg);
    }
}


function idCardInfo($card){
    $return['status'] = 0;

    $url = "http://www.cz88.net/tools/id.php";
    require_once  APP_ROOT_PATH."/system/utils/transport.php";
    $transport = new transport();
    $result = $transport->request($url,"in_id=".$card);
    $result = $result['body'];
    $result = iconv("gbk","utf-8",$result);
    $result =  str_replace(array("\r","\n"),"",$result);
    preg_match("/<div class=\"box\">  <div class=\"name\">发证地：<\/div>  <div class=\"data\">([^<>]+)<\/div> <\/div>/i",$result,$address);
    preg_match("/<div class=\"box\">  <div class=\"name\">出生日期：<\/div>  <div class=\"data\">([^<>]+)<\/div> <\/div>/i",$result,$birthday);
    preg_match("/<div class=\"box\">  <div class=\"name\">性别：<\/div>  <div class=\"data\">([^<>]+)<\/div> <\/div>/i",$result,$sex);
    preg_match("/<div class=\"box\">  <div class=\"name\">(\d+)位身份证号：<\/div>  <div class=\"data\">(.*?)<\/div> <\/div>/i",$result,$cardNO);

    $return = array();
    if(trim($birthday[1])=="" && trim($sex[1])=="" && trim($cardNO[2])==""){
        $return['status'] = 0;
        $return['info'] = "你输入的身份证号码错误，请重新输入。";
    }
    else{
        $return['address'] = $address[1];

        $return['birthday'] = $birthday[1];

        $return['sex'] = $sex[1];

        $return['cardNO'] = str_replace("&nbsp;","",strip_tags($cardNO[2]));

        $return['status'] = 1;
    }

    return $return;
}

/**
 * 获取几分钟内未支付的第三方托管投标金额
 * $left_time 分钟数  默认10分钟
 */
function getCollWaitMoney($deal,$left_time = 10){
    if($deal['ips_bill_no']==""){
        return 0;
    }
    else{
        $class = getCollName();
        $table="";
        $field="";
        $extwhere="";
        switch($class){
            case "Ips":
                $table="ips_register_creditor";
                $field="pTrdAmt";
                $extwhere=" AND (`pErrCode`='' or  ISNULL(`pErrCode`)) AND is_callback=0 and pBidNo='".$deal['id']."'";
                break;
            case "Baofoo":
                $table="baofoo_business";
                $field="load_amount";
                $extwhere=" AND (`code`='' or  ISNULL(`code`)) AND is_callback=0 and cus_id='".$deal['id']."'";
                break;
            case "Yeepay":
                $table="yeepay_cp_transaction";
                $field ="paymentAmount";
                $extwhere=" AND `bizType`='TENDER' AND ( `code`='' or  ISNULL(`code`)) AND is_callback=0 and tenderOrderNo='".$deal['id']."'";
                break;
            case "Fuioupay":
                $table="fuioupay_cp_transaction";
                $field ="paymentAmount";
                $extwhere=" AND `bizType`='TENDER' AND ( `code`='' or  ISNULL(`code`)) AND is_callback=0 and tenderOrderNo='".$deal['id']."'";
                //$left_time = 5;
                break;
        }

        if($table=="" || $field==""){
            return 0;
        }
        else{
            $wait_loadmoney = $GLOBALS['db']->getOne("SELECT sum(".$field.") FROM ".DB_PREFIX.$table." WHERE create_time + ".($left_time*60)." > ".TIME_UTC." ".$extwhere);

            return  floatval($wait_loadmoney);
        }
    }
}

/**
 * 过滤绑定用户名中的奇葩字符
 */
function filterEmoji($string){
    $string = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '',$string);
    return  preg_replace("/[^\x{4e00}-\x{9fa5}a-zA-Z\d]/iuU",'',$string);
}

//获取系统运行上传的值
function get_max_file_size(){
    $system_size=intval(ini_get("post_max_size"))<intval(ini_get("upload_max_filesize"))?intval(ini_get("post_max_size"))*1024*1024:intval(ini_get("upload_max_filesize"))*1024*1024;
    $config_size=app_conf("MAX_IMAGE_SIZE");
    $max_size = $system_size>$config_size?$config_size:$system_size;
    //number_format($system_size/(1024*1024),1)
    if($max_size>=1024*1024){
        return number_format($max_size/(1024*1024),1).'MB';
    }elseif($max_size>=1024){
        return number_format($max_size/(1024),1).'KB';
    }else{
        return $max_size.'B';
    }
}

//获取系统运行上传的值
function get_max_file_size_byte(){
    $system_size=intval(ini_get("post_max_size"))<intval(ini_get("upload_max_filesize"))?intval(ini_get("post_max_size"))*1024*1024:intval(ini_get("upload_max_filesize"))*1024*1024;
    $config_size=app_conf("MAX_IMAGE_SIZE");
    $max_size = $system_size>$config_size?$config_size:$system_size;
    return $max_size;
}

/**
 * 分页处理
 * @param string $type 所在页面
 * @param array  $args 参数
 * @param int $total_count 总数
 * @param int $page 当前页
 * @param int $page_size 分页大小
 * @param string $url 自定义路径
 * @param int $offset 偏移量
 * @return array
 */
function buildPage($type,$args,$total_count,$page = 1,$page_size = 0,$url='',$offset = 5){
    $pager['total_count'] = intval($total_count);
    $pager['page'] = $page;
    $pager['page_size'] = ($page_size == 0) ? 20 : $page_size;
    /* page 总数 */
    $pager['page_count'] = ($pager['total_count'] > 0) ? ceil($pager['total_count'] / $pager['page_size']) : 1;

    /* 边界处理 */
    if ($pager['page'] > $pager['page_count'])
        $pager['page'] = $pager['page_count'];

    $pager['limit'] = ($pager['page'] - 1) * $pager['page_size'] . "," . $pager['page_size'];
    $page_prev  = ($pager['page'] > 1) ? $pager['page'] - 1 : 1;
    $page_next  = ($pager['page'] < $pager['page_count']) ? $pager['page'] + 1 : $pager['page_count'];
    $pager['prev_page'] = $page_prev;
    $pager['next_page'] = $page_next;

    if (!empty($url)){
        $pager['page_first'] = $url . 1;
        $pager['page_prev']  = $url . $page_prev;
        $pager['page_next']  = $url . $page_next;
        $pager['page_last']  = $url . $pager['page_count'];
    }
    else{
        $args['page'] = '_page_';
        if(!empty($type)){
            if(strpos($type,'javascript:') === false){
                //$page_url = JKU($type,$args);
                $page_url = u($type,$args);
            }else{
                $page_url = $type;

            }
        }else{
            $page_url = 'javascript:;';
        }
        $pager['page_first'] = str_replace('_page_',1,$page_url);
        $pager['page_prev']  = str_replace('_page_',$page_prev,$page_url);
        $pager['page_next']  = str_replace('_page_',$page_next,$page_url);
        $pager['page_last']  = str_replace('_page_',$pager['page_count'],$page_url);
    }
    $pager['page_nums'] = array();
    if($pager['page_count'] <= $offset * 2){
        for ($i=1; $i <= $pager['page_count']; $i++){
            $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
        }
    }else{
        if($pager['page'] - $offset < 2){
            $temp = $offset * 2;
            for ($i=1; $i<=$temp; $i++){
                $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
            }
            $pager['page_nums'][] = array('name'=>'...');
            $pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
        }else{
            $pager['page_nums'][] = array('name' => 1,'url' => empty($url) ? str_replace('_page_',1,$page_url) : $url . 1);
            $pager['page_nums'][] = array('name'=>'...');
            $start = $pager['page'] - $offset + 1;
            $end = $pager['page'] + $offset - 1;
            if($pager['page_count'] - $end > 1){
                for ($i=$start;$i<=$end;$i++){
                    $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
                }

                $pager['page_nums'][] = array('name'=>'...');
                $pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
            }else{
                $start = $pager['page_count'] - $offset * 2 + 1;
                $end = $pager['page_count'];
                for ($i=$start;$i<=$end;$i++){
                    $pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
                }
            }
        }
    }
    return $pager;
}


function parse_url_tag_coomon($str)
{
    $str = substr($str,2);
    $str_array = explode("|",$str);
    $app_index = $str_array[0];
    $route = $str_array[1];
    $param_tmp = explode("&",$str_array[2]);
    $param = array();
    foreach($param_tmp as $item)
    {
        if($item!='')
            $item_arr = explode("=",$item);
        if($item_arr[0]&&$item_arr[1])
            $param[$item_arr[0]] = $item_arr[1];
    }
    return wap_url("index",$route,$param);
}

//解析URL标签
// $str = u:shop|acate#index|id=10&name=abc
function parse_url_tag($str)
{
    $key = md5("URL_TAG_".$str);
    if(isset($GLOBALS[$key]))
    {
        return $GLOBALS[$key];
    }

    $url = load_dynamic_cache($key);
    if($url!==false)
    {
        $GLOBALS[$key] = $url;
        return $url;
    }
    $str = substr($str,2);
    $str_array = explode("|",$str);
    $app_index = $str_array[0];
    $route = $str_array[1];
    $param_tmp = explode("&",$str_array[2]);
    $param = array();
    foreach($param_tmp as $item)
    {
        if($item!='')
            $item_arr = explode("=",$item);
        if($item_arr[0]&&$item_arr[1])
            $param[$item_arr[0]] = $item_arr[1];
    }
    $GLOBALS[$key]= url($app_index,$route,$param);
    set_dynamic_cache($key,$GLOBALS[$key]);
    return $GLOBALS[$key];
}

function parse_url_tag_wap($str)
{
    $key = md5("URL_TAG_".$str);
    if(isset($GLOBALS[$key]))
    {
        return $GLOBALS[$key];
    }

    $url = load_dynamic_cache($key);
    if($url!==false)
    {
        $GLOBALS[$key] = $url;
        return $url;
    }
    $str = substr($str,2);
    $str_array = explode("|",$str);
    $route = $str_array[0];
    $param_tmp = explode("&",$str_array[1]);
    $param = array();
    foreach($param_tmp as $item)
    {
        if($item!='')
            $item_arr = explode("=",$item);
        if($item_arr[0]&&$item_arr[1])
            $param[$item_arr[0]] = $item_arr[1];
    }
    $GLOBALS[$key]= url_wap($route,$param);
    set_dynamic_cache($key,$GLOBALS[$key]);
    return $GLOBALS[$key];
}

//获取用户头像的文件名WAP
function wap_user_avatar($id,$type="middle")
{
    $uid = sprintf("%09d", $id);
    $dir1 = substr($uid, 0, 3);
    $dir2 = substr($uid, 3, 2);
    $dir3 = substr($uid, 5, 2);
    $path = $dir1.'/'.$dir2.'/'.$dir3;

    $id = str_pad($id, 2, "0", STR_PAD_LEFT);
    $id = substr($id,-2);
    $avatar_file = APP_ROOT."/public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    $avatar_file = str_replace(array("wap/","mapi/"),"",$avatar_file);
    $avatar_check_file = APP_ROOT_PATH."public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    $avatar_check_file = str_replace(array("wap/","mapi/"),"",$avatar_check_file);
    if(file_exists($avatar_check_file))
        return $avatar_file;
    else{
        return  SITE_DOMAIN.str_replace(array("/wap","/mapi"),"",APP_ROOT)."/wap/tpl/fanwe/images/login_out.png";
    }
}

//微信通知
function weixin_tmpl_send($template_id,$user_id,$weixin_data){
    require_once APP_ROOT_PATH."system/wechat/platform_wechat.class.php";
    $weixin_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id='$template_id' ");
    $user_info = get_user_info("*","id = ".$user_id);

    if($weixin_tmpl['template_id']){
        $weixin_conf = load_auto_cache("weixin_conf");

        $account = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_account where type=1 and user_id = 0 ");

        $option = array(
            'platform_token'=>$weixin_conf['platform_token'], //填写你设定的token
            'platform_encodingAesKey'=>$weixin_conf['platform_encodingAesKey'], //填写加密用的EncodingAESKey
            'platform_appid'=>$weixin_conf['platform_appid'], //填写高级调用功能的app id
            'platform_appsecret'=>$weixin_conf['platform_appsecret'], //填写高级调用功能的密钥

            'platform_component_verify_ticket'=>$weixin_conf['platform_component_verify_ticket'], //第三方通知
            'platform_component_access_token'=>$weixin_conf['platform_component_access_token'], //第三方平台令牌
            'platform_pre_auth_code'=>$weixin_conf['platform_pre_auth_code'], //第三方平台预授权码

            'platform_component_access_token_expire'=>$weixin_conf['platform_component_access_token_expire'],
            'platform_pre_auth_code_expire'=>$weixin_conf['platform_pre_auth_code_expire'],

            'logcallback'=>'log_result',
            'debug'=>true,
        );
        if($account){
            $option_account=array(
                'authorizer_access_token'=>$account['authorizer_access_token'],
                'authorizer_access_token_expire'=>$account['expires_in'],
                'authorizer_appid'=>$account['authorizer_appid'],
                'authorizer_refresh_token'=>$account['authorizer_refresh_token'],
            );

            $option=array_merge($option,$option_account);
            $platform = new PlatformWechat($option);
            $platform->check_platform_authorizer_token();

            $data=unserialize($weixin_tmpl['msg']);
            //订单支付成功通知
            if($weixin_tmpl['template_id_short']=='OPENTM207791277'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                //投标结果通知
            }elseif($weixin_tmpl['template_id_short']=='OPENTM200685723'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                //提现成功通知
            }elseif($weixin_tmpl['template_id_short']=='TM00980'){
                $data['first'] = $weixin_data['first'];
                $data['money'] = $weixin_data['money'];
                $data['timet'] = $weixin_data['timet'];
                //还款信息通知
            }elseif($weixin_tmpl['template_id_short']=='OPENTM205975633'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                //成功获取额度通知
            }elseif($weixin_tmpl['template_id_short']=='OPENTM207582660'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                //回款通知
            }elseif($weixin_tmpl['template_id_short']=='OPENTM207940989'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                $data['keyword3'] = $weixin_data['keyword3'];
                //贷款还款提醒
            }elseif($weixin_tmpl['template_id_short']=='OPENTM400811886'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
                //借款审核结果通知
            }elseif($weixin_tmpl['template_id_short']=='OPENTM204320762'){
                $data['first'] = $weixin_data['first'];
                $data['keyword1'] = $weixin_data['keyword1'];
                $data['keyword2'] = $weixin_data['keyword2'];
            }
            else{
                $data['keyword1']=array('value'=>'keyword1','color'=>'#173177');
                $data['keyword2']=array('value'=>'keyword2','color'=>'#173177');
                $data['keyword3']=array('value'=>'keyword3','color'=>'#173177');
            }
            $info=array(
                'touser'=>$user_info['wx_openid'],
                'template_id'=>$weixin_tmpl['template_id'],
                'url'=>get_domain().url_wap("index"),
                'topcolor'=>'#FF0000',
                'data'=>$data
            );
            $result=$platform->sendTemplateMessage($info);
//				$tmpl_content = $weixin_tmpl['content'];
//				$msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);

            $wx_msg_data['dest'] = $user_info['wx_openid'];
            $wx_msg_data['send_type'] = 3;
            $wx_msg_data['user_id'] = $user_id;
            $wx_msg_data['title'] = $weixin_tmpl['name'];
            $wx_msg_data['create_time'] = TIME_UTC;

            $wx_msg_data['content'] = serialize($info);
            //$wx_msg_data['content'] = addslashes($msg);;

            if($result){
                $wx_msg_data['is_send'] = 1;
                if(isset($result['errcode'])&&$result['errcode']>0){
                    $wx_msg_data['send_time'] = TIME_UTC;
                    $wx_msg_data['is_success'] = 0;
                    $wx_msg_data['result'] = "发送失败".$result['errcode'].":".$result['errmsg'];
                    //$this->error("发送失败".$result['errcode'].":".$result['errmsg'],$this->isajax);

                }else{
                    $wx_msg_data['send_time'] = TIME_UTC;
                    $wx_msg_data['is_success'] = 1;
                    $wx_msg_data['result'] = "发送成功";
                    //$this->success('发送成功',$this->isajax);
                }

            }else{
                $wx_msg_data['result'] = "通讯失败";
                $wx_msg_data['is_success'] = 0;
                $wx_msg_data['is_send'] = 0;
                //return 0;
                //$this->error("通讯失败");
            }
            $GLOBALS['db']->autoExecute(DB_PREFIX."weixin_msg_list",$wx_msg_data);
        }

    }
}

//3.0修改 start
/**
 * 获取毫秒
 */
function get_microtime(){
    list($usec, $sec) = explode(" ", microtime());
    $microtime = ((int)($usec * 1000) + (float)$sec * 1000);
    return $microtime;
}


function checkVeifyCode($code,$vname="verify"){
    require_once APP_ROOT_PATH."system/utils/Verify.class.php";
    $verify = new Verify ();
    return $verify->check($code,$vname);
}

function isApp(){
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $is_app = strpos($agent, 'fanwe_app_sdk') ? true : false ;
    if($is_app){
        return true;
    }else{
        return false;
    }
}

//过滤请求
filter_request($_REQUEST);
filter_request($_GET);
filter_request($_POST);
define("AUTH_NOT_LOGIN", 1); //未登录的常量
define("AUTH_NOT_AUTH", 2);  //未授权常量

// 全站公共函数库
// 更改系统配置, 当更改数据库配置时为永久性修改， 修改配置文档中配置为临时修改
function conf2($name,$value = false)
{
    if($value === false)
    {
        return C($name);
    }
    else
    {
        if(M("Conf")->where("is_effect=1 and name='".$name."'")->count()>0)
        {
            if(in_array($name,array('EXPIRED_TIME','SUBMIT_DELAY','SEND_SPAN','WATER_ALPHA','MAX_IMAGE_SIZE','INDEX_LEFT_STORE','INDEX_LEFT_TUAN','INDEX_LEFT_YOUHUI','INDEX_LEFT_DAIJIN','INDEX_LEFT_EVENT','INDEX_RIGHT_STORE','INDEX_RIGHT_TUAN','INDEX_RIGHT_YOUHUI','INDEX_RIGHT_DAIJIN','INDEX_RIGHT_EVENT','SIDE_DEAL_COUNT','DEAL_PAGE_SIZE','PAGE_SIZE','BATCH_PAGE_SIZE','HELP_CATE_LIMIT','HELP_ITEM_LIMIT','REC_HOT_LIMIT','REC_NEW_LIMIT','REC_BEST_LIMIT','REC_CATE_GOODS_LIMIT','SALE_LIST','INDEX_NOTICE_COUNT','RELATE_GOODS_LIMIT')))
            {
                $value = intval($value);
            }
            M("Conf")->where("is_effect=1 and name='".$name."'")->setField("value",$value);
        }
        C($name,$value);
    }
}


// 错误输出
function halt($error) {
    if(IS_CLI)   exit ($error);
    $e = array();
    if(C('APP_DEBUG')){
        //调试模式下输出错误信息
        if(!is_array($error)) {
            $trace = debug_backtrace();
            $e['message'] = $error;
            $e['file'] = $trace[0]['file'];
            $e['class'] = $trace[0]['class'];
            $e['function'] = $trace[0]['function'];
            $e['line'] = $trace[0]['line'];
            $traceInfo='';
            $time = date("y-m-d H:i:m");
            foreach($trace as $t)
            {
                $traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
                $traceInfo .= $t['class'].$t['type'].$t['function'].'(';
                $traceInfo .= implode(', ', $t['args']);
                $traceInfo .=")<br/>";
            }
            $e['trace']  = $traceInfo;
        }else {
            $e = $error;
        }
        // 包含异常页面模板
        include C('TMPL_EXCEPTION_FILE');
    }
    else
    {
        //否则定向到错误页面
        $error_page =   C('ERROR_PAGE');
        if(!empty($error_page)){
            redirect($error_page);
        }else {
            if(C('SHOW_ERROR_MSG'))
                $e['message'] =  is_array($error)?$error['message']:$error;
            else
                $e['message'] = C('ERROR_MESSAGE');
            // 包含异常页面模板
            include C('TMPL_EXCEPTION_FILE');
        }
    }
    exit;
}


function get_all_files( $path )
{
    $list = array();
    $dir = @opendir($path);
    while (false !== ($file = @readdir($dir)))
    {
        if($file!='.'&&$file!='..')
            if( is_dir( $path.$file."/" ) ){
                $list = array_merge( $list , get_all_files( $path.$file."/" ) );
            }
            else
            {
                $list[] = $path.$file;
            }
    }
    @closedir($dir);
    return $list;
}
function get_order_item_name($id)
{
    return M("DealOrderItem")->where("id=".$id)->getField("name");
}
function get_supplier_name($id)
{
    return M("Supplier")->where("id=".$id)->getField("name");
}

function get_send_type_msg($status)
{
    if($status==0)
    {
        return l("SMS_SEND");
    }
    else
    {
        return l("MAIL_SEND");
    }
}
function show_content($content,$id)
{
    return "<a title='".l("VIEW")."' href='javascript:void(0);' onclick='show_content(".$id.")'>".l("VIEW")."</a>";
}



function get_is_send($is_send)
{
    if($is_send==0)
        return L("NO");
    else
        return L("YES");
}
function get_send_result($result)
{
    if($result==0)
    {
        return L("FAILED");
    }
    else
    {
        return L("SUCCESS");
    }
}

function get_is_buy($is_buy)
{
    return l("IS_BUY_".$is_buy);
}

function get_point($point)
{
    return l("MESSAGE_POINT_".$point);
}

function get_status($status)
{
    if($status)
    {
        return l("YES");
    }
    else
        return l("NO");
}


function getMPageName($page)
{
    return L('MPAGE_'.strtoupper($page));
}

function getMTypeName($type)
{
    return L('MTYPE_'.strtoupper($type));
}
function get_submit_user($uid)
{
    if($uid==0)
        return "管理员发布";
    else
    {
        $uname = M("SupplierAccount")->where("id=".$uid)->getField("account_name");
        return $uname?$uname:"商家不存在";
    }

}
function get_event_cate_name($id)
{
    return M("EventCate")->where("id=".$id)->getField("name");
}

function write_timezone($zone='')
{
    if($zone=='')
        $zone = conf('TIME_ZONE');
    $var = array(
        '0'	=>	'UTC',
        '8'	=>	'PRC',
    );

    //开始将$db_config写入配置
    $timezone_config_str 	 = 	"<?php\r\n";
    $timezone_config_str	.=	"return array(\r\n";
    $timezone_config_str.="'DEFAULT_TIMEZONE'=>'".$var[$zone]."',\r\n";

    $timezone_config_str.=");\r\n";
    $timezone_config_str.="?>";

    @file_put_contents(get_real_path()."public/timezone_config.php",$timezone_config_str);
}



//后台日志记录
function save_log($msg,$status)
{
    if(conf("ADMIN_LOG")==1)
    {
        $adm_session = es_session::get(md5(conf("AUTH_KEY")));
        $log_data['log_info'] = $msg;
        $log_data['log_time'] = TIME_UTC;
        $log_data['log_admin'] = intval($adm_session['adm_id']);
        $log_data['log_ip']	= CLIENT_IP;
        $log_data['log_status'] = $status;
        $log_data['module']	=	MODULE_NAME;
        $log_data['action'] = 	ACTION_NAME;
        M("Log")->add($log_data);
    }
}


//状态的显示
function get_toogle_status($tag,$id,$field)
{
    if($tag)
    {
        return "<span class='is_effect' onclick=\"toogle_status(".$id.",this,'".$field."');\">".l("YES")."</span>";
    }
    else
    {
        return "<span class='is_effect' onclick=\"toogle_status(".$id.",this,'".$field."');\">".l("NO")."</span>";
    }
}



//状态的显示
function get_is_effect($tag,$id)
{
    if($tag)
    {
        return "<span class='is_effect' onclick='set_effect(".$id.",this);'>".l("IS_EFFECT_1")."</span>";
    }
    else
    {
        return "<span class='is_effect' onclick='set_effect(".$id.",this);'>".l("IS_EFFECT_0")."</span>";
    }
}

//状态的显示
function get_is_new($tag,$id)
{
    if($tag)
    {
        return "<span class='is_new' onclick='set_new(".$id.",this);'>".l("IS_NEW_1")."</span>";
    }
    else
    {
        return "<span class='is_new' onclick='set_new(".$id.",this);'>".l("IS_NEW_0")."</span>";
    }
}


//排序显示
function get_sort($sort,$id)
{
    if($tag)
    {
        return "<span class='sort_span' onclick='set_sort(".$id.",".$sort.",this);'>".$sort."</span>";
    }
    else
    {
        return "<span class='sort_span' onclick='set_sort(".$id.",".$sort.",this);'>".$sort."</span>";
    }
}

//推荐排序
function get_isrec($is_rec,$id)
{
    if($tag)
    {
        return "<span class='is_rec' onclick='set_isrec(".$id.",".$is_rec.",this);'>".$is_rec."</span>";
    }
    else
    {
        return "<span class='is_rec' onclick='set_isrec(".$id.",".$is_rec.",this);'>".$is_rec."</span>";
    }
}

function get_nav($nav_id)
{
    return M("RoleNav")->where("id=".$nav_id)->getField("name");
}
function get_module($module_id)
{
    return M("RoleModule")->where("id=".$module_id)->getField("module");
}
function get_group($group_id)
{
    if($group_data = M("RoleGroup")->where("id=".$group_id)->find())
        $group_name = $group_data['name'];
    else
        $group_name = L("SYSTEM_NODE");
    return $group_name;
}
function get_role_name($role_id)
{
    return M("Role")->where("id=".$role_id)->getField("name");
}
function get_admin_name($admin_id)
{
    $adm_name = M("Admin")->where("id=".$admin_id)->getField("adm_name");
    if($adm_name)
        return $adm_name;
    else
        return l("NONE_ADMIN_NAME");
}
function get_log_status($status)
{
    return l("LOG_STATUS_".$status);
}
//验证相关的函数
//验证排序字段
function check_sort($sort)
{
    if(!is_numeric($sort))
    {
        return false;
    }
    if(intval($sort)<=0)
    {
        return false;
    }
    return true;
}
function check_empty($data)
{
    if(trim($data)=='')
    {
        return false;
    }
    return true;
}

function set_default($null,$adm_id)
{

    $admin_name = M("Admin")->where("id=".$adm_id)->getField("adm_name");
    if($admin_name == conf("DEFAULT_ADMIN"))
    {
        return "<span style='color:#f30;'>".l("DEFAULT_ADMIN")."</span>";
    }
    else
    {
        return "<a href='".u("Admin/set_default",array("id"=>$adm_id))."'>".l("SET_DEFAULT_ADMIN")."</a>";
    }
}
function get_order_sn($order_id)
{
    return M("DealOrder")->where("id=".$order_id)->getField("order_sn");
}
function get_order_sn_with_link($order_id)
{
    $order_info = M("DealOrder")->where("id=".$order_id)->find();
    if($order_info['type']==0)
        $str = l("DEAL_ORDER_TYPE_0")."：<a href='".u("DealOrder/deal_index",array("order_sn"=>$order_info['order_sn']))."'>".$order_info['order_sn']."</a>";
    else
        $str = l("DEAL_ORDER_TYPE_1")."：<a href='".u("DealOrder/incharge_index",array("order_sn"=>$order_info['order_sn']))."'>".$order_info['order_sn']."</a>";

    if($order_info['is_delete']==1)
        $str ="<span style='text-decoration:line-through;'>".$str."</span>";
    return $str;
}
function get_user_name($user_id)
{
    $user_info =  M("User")->where("id=".$user_id." and is_delete = 0")->Field("user_name,user_type")->find();

    if(!$user_info)
        return l("NO_USER");
    else
        return "<a href='".u("User/".($user_info['user_type']==0? "index" : "company_index"),array("user_name"=>$user_info['user_name']))."' target='_blank'>".$user_info['user_name']."</a>";

}

function get_user_name_real($user_id){
    $user_info =  M("User")->where("id=".$user_id." and is_delete = 0")->Field("user_name,AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name,user_type")->find();
    if(!$user_info)
        return l("NO_USER");
    else
        return "<a href='".u("User/".($user_info['user_type']==0? "index" : "company_index"),array("user_name"=>$user_info['user_name']))."' target='_blank'>".$user_info['user_name'].($user_info['real_name']!="" ? "[".$user_info['real_name']."]":"")."</a>";
}

function get_user_name_reals($user_id){
    $user_info =  M("User")->where("id=".$user_id." and is_delete = 0")->Field("user_name,AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name")->find();
    if(!$user_info)
        return l("NO_USER");
    else
        return $user_info['user_name'].($user_info['real_name']!="" ? "[".$user_info['real_name']."]":"");
}

function get_user_name_js($user_id)
{
    $user_name =  M("User")->where("id=".$user_id." and is_delete = 0")->getField("AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name");

    if(!$user_name)
        return l("NO_USER");
    else
        return "<a href='javascript:void(0);' onclick='account(".$user_id.")'>".$user_name."</a>";


}
function get_pay_status($status)
{
    return L("PAY_STATUS_".$status);
}
function get_delivery_status($status,$order_id)
{
    //,notice_sn|get_notice_info=$deal_order['notice_id']:{%DELIVERY_SN}
    $order_item_ids = $GLOBALS['db']->getOne("select group_concat(id) from ".DB_PREFIX."deal_order_item where order_id = ".intval($order_id));
    if(!$order_item_ids)
        $order_item_ids = 0;
    $rs = $GLOBALS['db']->getAll("select dn.notice_sn,dn.id from ".DB_PREFIX."delivery_notice as dn where dn.order_item_id in (".$order_item_ids.") ");
    $result = "";
    foreach($rs as $row)
    {
        $result .= "&nbsp;".get_notice_info($row['notice_sn'],$row['id'])."<br />";
    }
    return L("ORDER_DELIVERY_STATUS_".$status)."<br />".$result;
}
function get_notice_info($sn,$notice_id)
{
    $express_name = M()->query("select e.name as ename from ".DB_PREFIX."express as e left join ".DB_PREFIX."delivery_notice as dn on dn.express_id = e.id where dn.id = ".$notice_id);
    $express_name = $express_name[0]['ename'];
    if($express_name)
        $str = $express_name."<br/>&nbsp;".$sn;
    else
        $str = $sn;
    return $str;
}


function get_payment_name($payment_id)
{
    return M("Payment")->where("id=".$payment_id)->getField("name");
}
function get_delivery_name($delivery_id)
{
    return M("Delivery")->where("id=".$delivery_id)->getField("name");
}
function get_region_name($region_id)
{
    return M("DeliveryRegion")->where("id=".$region_id)->getField("name");
}
function get_city_name($id)
{
    return M("DealCity")->where("id=".$id)->getField("name");
}

function get_message_type($type_name,$rel_id)
{
    $show_name = M("MessageType")->where("type_name='".$type_name."'")->getField("show_name");
    if($type_name=='deal_order')
    {
        $order_sn = M("DealOrder")->where("id=".$rel_id)->getField("order_sn");
        if($order_sn)
            return "[".$order_sn."] <a href='".u("DealOrder/deal_index",array("id"=>$rel_id))."'>".$show_name."</a>";
        else
            return $show_name;
    }
    elseif($type_name=='deal')
    {
        $sub_name = M("Deal")->where("id=".$rel_id)->getField("sub_name");
        if($sub_name)
            return "[".$sub_name."]" .$show_name;
        else
            return $show_name;
    }
    elseif($type_name=='supplier')
    {
        $name = M("Supplier")->where("id=".$rel_id)->getField("name");
        if($name)
            return "[".$name."] <a href='".u("Supplier/index",array("id"=>$rel_id))."'>".$show_name."</a>";
        else
            return $show_name;
    }
    else
    {
        if($show_name)
            return $show_name;
        else
            return $type_name;
    }
}

function get_send_status($status)
{
    return L("SEND_STATUS_".$status);
}
function get_send_mail_type($deal_id)
{
    if($deal_id>0)
        return l("DEAL_NOTICE");
    else
        return l("COMMON_NOTICE");
}
function get_send_type($send_type)
{
    return l("SEND_TYPE_".$send_type);
}

function get_deal_user($uid)
{
    $uinfo = M("User")->getById($uid);
    if($uinfo)
    {
        return $uinfo['user_name'];
    }
    else
    {
        if($uid==0)
            return "管理员发起";
        else
            return "发起人被删除";
    }
}
function get_to_date($time)
{
    if($time==0)return "长期";
    if($time<get_gmtime())
    {
        return "<span style='color:#f30;'>过期</span>";
    }
    else
    {
        return  "<span>".to_date($time,"Y/m/d H:i")."</span>";
    }
}

/**
 * 写系统配置
 */
function write_sys_conf(){
    $return =  array("status"=>0,"info"=>"");
    //开始写入配置文件
    $sys_configs = M("Conf")->findAll();
    $sys_config =array();
    foreach($sys_configs as $k=>$v){
        $sys_config[$v['name']] = $v['value'];
    }

    $config = array();

    $config = array_merge($config,$sys_config);

    //加载系统信息
    $version	=	require APP_ROOT_PATH.'public/version.php';
    $config = array_merge($config,$version);


    //加载时区信息
    $timezone	=	require APP_ROOT_PATH.'public/timezone_config.php';
    $config = array_merge($config,$timezone);


    // 加载数据库中的配置与数据库配置
    $db_config	=	require APP_ROOT_PATH.'public/db_config.php';
    $config = array_merge($config,$db_config);


    $config_str = "<?php\n";
    $config_str .= "return array(\n";
    foreach($config as $k=>$v)
    {
        $config_str.="'".$k."'=>'".addslashes($v)."',\n";
    }
    $config_str.=");\n ?>";

    $filename = APP_ROOT_PATH."public/sys_config.php";
    if (!$handle = fopen($filename, 'w')) {
        $return['info'] = l("OPEN_FILE_ERROR").$filename;
        return $return;
    }


    if (fwrite($handle, $config_str) === FALSE) {
        $return['info'] = l("WRITE_FILE_ERROR").$filename;
        return $return;
    }



    return array("status"=>1,"info"=>"");
}

//app项目用到的函数库

/**
 * 获取页面的标题，关键词与描述
 */
function get_site_info()
{
    $shop_info['SHOP_TITLE']	=	app_conf('SHOP_TITLE');
    $shop_info['SHOP_KEYWORD']	=	app_conf('SHOP_KEYWORD');
    $shop_info['SHOP_DESCRIPTION']	=	app_conf('SHOP_DESCRIPTION');
    return $shop_info;
}

/**
 * 获取导航菜单
 */
function format_nav_list($nav_list)
{
    foreach($nav_list as $k=>$v)
    {
        if(trim($v['url'])!='')
        {
            if(substr($v['url'],0,7)!="http://" && substr($v['url'],0,8)!="https://" )
            {
                //开始分析url
                $nav_list[$k]['url'] = APP_ROOT."/".$v['url'];
            }
        }
        else
        {
            preg_match("/id=(\d+)/i",$v['u_param'],$matches);
            $id = intval($matches[1]);
            if($v['u_module']=='article'&&$id>0)
            {
                $article = get_article($id);
                if($article['type_id']==1)
                {
                    $nav_list[$k]['u_module'] = "help";
                }
                elseif($article['type_id']==2)
                {
                    $nav_list[$k]['u_module'] = "notice";
                }
                elseif($article['type_id']==3)
                {
                    $nav_list[$k]['u_module'] = "sys";
                }
                else
                {
                    $nav_list[$k]['u_module'] = 'article';
                }
            }
        }
    }
    return $nav_list;
}
function get_nav_list()
{
    return load_auto_cache("cache_nav_list");
}

function init_nav_list($nav_list)
{
    $u_param = "";
    foreach($_GET as $k=>$v)
    {
        if(strtolower($k)!="ctl"&&strtolower($k)!="act"&&strtolower($k)!="city")
        {
            $u_param.=$k."=".$v."&";
        }
    }
    if(substr($u_param,-1,1)=='&')
        $u_param = substr($u_param,0,-1);
    foreach($nav_list as $k=>$v)
    {
        if(trim($v['url'])=='')
        {
            $route = $v['u_module'];
            if($v['u_action']!='')
                $route.="#".$v['u_action'];

            $app_index = $v['app_index'];

            if($v['u_module']=='index')
            {
                $route="index";
                $v['u_module'] = "index";
            }

            if($v['u_action']=='')
                $v["u_action"] = "index";

            $str = "u:".$app_index."|".$route."|".$v['u_param'];
            $nav_list[$k]['url'] =  parse_url_tag($str);
            if(($v['u_module']=='deals' || $v['u_module']=='transfer' || $v['u_module']=='tool') && MODULE_NAME==$v['u_module']){
                $nav_list[$k]['current'] = 1;
            }
            elseif($v['u_module']=='borrow' && MODULE_NAME==$v['u_module']){
                $nav_list[$k]['current'] = 1;
            }
            elseif(ACTION_NAME==$v['u_action']&&MODULE_NAME==$v['u_module']&&$v['u_param']==$u_param)
            {
                $nav_list[$k]['current'] = 1;
            }
        }
    }
    return $nav_list;
}

function get_help()
{
    return load_auto_cache("get_help_cache");
}



//获取所有子集的类
class ChildIds
{
    public function __construct($tb_name)
    {
        $this->tb_name = $tb_name;
    }
    private $tb_name;
    private $childIds;
    private function _getChildIds($pid = '0', $pk_str='id' , $pid_str ='pid')
    {
        $childItem_arr = $GLOBALS['db']->getAll("select id from ".DB_PREFIX.$this->tb_name." where ".$pid_str."=".intval($pid));
        if($childItem_arr)
        {
            foreach($childItem_arr as $childItem)
            {
                $this->childIds[] = $childItem[$pk_str];
                $this->_getChildIds($childItem[$pk_str],$pk_str,$pid_str);
            }
        }
    }
    public function getChildIds($pid = '0', $pk_str='id' , $pid_str ='pid')
    {
        $this->childIds = array();
        $this->_getChildIds($pid,$pk_str,$pid_str);
        return $this->childIds;
    }
}

//显示错误
function showErr($msg,$ajax=0,$jump='',$stay=0,$from="")
{
    if($ajax==1)
    {
        $result['status'] = 0;
        $result['info'] = $msg;
        $result['jump'] = $jump;
        header("Content-Type:text/html; charset=utf-8");
        echo(json_encode($result));exit;
    }
    else
    {

        $GLOBALS['tmpl']->assign('page_title',$GLOBALS['lang']['ERROR_TITLE']." - ".$msg);
        $GLOBALS['tmpl']->assign('msg',$msg);
        if($jump=='')
        {
            $jump = $_SERVER['HTTP_REFERER'];
        }
        if(!$jump&&$jump=='')
            $jump = APP_ROOT."/";
        $GLOBALS['tmpl']->assign('jump',$jump);
        $GLOBALS['tmpl']->assign("stay",$stay);
        if($from == "debit")
        {
            $GLOBALS['tmpl']->display("debit/debit_error.html");
        }
        else
        {
            $GLOBALS['tmpl']->display("error.html");
        }
        exit;
    }
}

//显示成功
function showSuccess($msg,$ajax=0,$jump='',$stay=0,$from="")
{
    if($ajax==1)
    {
        $result['status'] = 1;
        $result['info'] = $msg;
        $result['jump'] = $jump;
        header("Content-Type:text/html; charset=utf-8");
        echo(json_encode($result));exit;
    }
    else
    {
        $GLOBALS['tmpl']->assign('page_title',$GLOBALS['lang']['SUCCESS_TITLE']." - ".$msg);
        $GLOBALS['tmpl']->assign('msg',$msg);
        if($jump=='')
        {
            $jump = $_SERVER['HTTP_REFERER'];
        }
        if(!$jump&&$jump=='')
            $jump = APP_ROOT."/";
        $GLOBALS['tmpl']->assign('jump',$jump);
        $GLOBALS['tmpl']->assign("stay",$stay);
        if($from == "debit")
        {
            $GLOBALS['tmpl']->display("debit/debit_success.html");
        }
        else if($from == "sign_fdd"){
            $GLOBALS['tmpl']->display("debit/sign_fdd_success.html");
        }
        else
        {
            $GLOBALS['tmpl']->display("success.html");
        }
        exit;
    }
}


//显示IPS成功
function showSuccessIPS($msg,$ajax=0,$jump='',$stay=0,$from="")
{
    if($ajax==1)
    {
        $result['status'] = 1;
        $result['info'] = $msg;
        $result['jump'] = $jump;
        header("Content-Type:text/html; charset=utf-8");
        echo(json_encode($result));exit;
    }
    else
    {
        $GLOBALS['tmpl']->assign('page_title',$GLOBALS['lang']['SUCCESS_TITLE']." - ".$msg);
        $GLOBALS['tmpl']->assign('msg',$msg);
        if($jump=='')
        {
            $jump = $_SERVER['HTTP_REFERER'];
        }
        if(!$jump&&$jump=='')
            $jump = APP_ROOT."/";
        $GLOBALS['tmpl']->assign('jump',$jump);
        $GLOBALS['tmpl']->assign("stay",$stay);
        if($from == "debit")
        {
            $GLOBALS['tmpl']->display("debit/debit_success.html");
        }
        else
        {
            $GLOBALS['tmpl']->display("success_ips.html");
        }
        exit;
    }
}

/**
 * 获取用户名
 */
if(!function_exists("get_user_name")){
    function get_user_name($id,$show_tag=true)
    {
        $key = md5("USER_NAME_LINK_".$id."_".$show_tag);
        if(isset($GLOBALS[$key]))
        {
            return $GLOBALS[$key];
        }
        else
        {
            $uname = load_dynamic_cache($key);
            if($uname===false)
            {
                $u = get_user_info("id,user_name","id = ".intval($id));
                if($show_tag)
                    $uname = "<a href='".url("index","space",array("id"=>$id))."'  class='user_name'  onmouseover='userCard.load(this,".$u['id'].");' >".$u['user_name']."</a>";
                else
                    $uname = $u['user_name'];
                set_dynamic_cache($key,$uname);
            }
            $GLOBALS[$key] = $uname;
            return $GLOBALS[$key];
        }
    }
}

/**
 * 获取用户相应字段内容
 */
function get_user($extfield,$uid){
    $key = md5("USER_FILED_INFO_".$extfield.$uid);
    if(isset($GLOBALS[$key]))
    {
        return $GLOBALS[$key];
    }
    else
    {
        $user = load_dynamic_cache($key);
        if($user===false)
        {
            $user = get_user_info($extfield,"id = ".intval($uid));
            if($user){
                $user['point_level'] = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."user_level where id = ".intval($user['level_id']));
                $user['url'] = url("index","space",array("id"=>$uid));
                if($user['city_id'])
                    $user['region'] = $user['region_city'] = $GLOBALS['db']->getOne("select name from  ".DB_PREFIX."region_conf where id = ".intval($user['city_id']));

                if($user['province_id']){
                    $user['region_province'] = $GLOBALS['db']->getOne("select name from  ".DB_PREFIX."region_conf where id = ".intval($user['province_id']));
                    if(!$user['region'])
                        $user['region'] = $user['region_province'];
                }
                if($user['id']){
                    $user['workinfo'] = $GLOBALS['db']->getRow("select * from  ".DB_PREFIX."user_work where user_id = ".intval($user['id']));
                    if($user['workinfo']){
                        $user['workinfo']['region_province'] = $GLOBALS['db']->getOne("select name from  ".DB_PREFIX."region_conf where id = ".intval($user['workinfo']['province_id']));
                        $user['workinfo']['region_city'] = $GLOBALS['db']->getOne("select name from  ".DB_PREFIX."region_conf where id = ".intval($user['workinfo']['city_id']));
                    }
                }

            }
            set_dynamic_cache($key,$user);
        }
        $GLOBALS[$key] = $user;
        return $GLOBALS[$key];
    }
}

/**
 * 获取用户所上传的认证材料
 */
function get_user_credit_file($uid,$user_info=false,$cache=true){
    $key = md5("USER_CREDIT_FILE_".$uid);
    if(isset($GLOBALS[$key]) && $cache==true)
    {
        return $GLOBALS[$key];
    }
    else
    {
        if($cache==true)
            $user_credit_file = load_dynamic_cache($key);
        else
            $user_credit_file = false;
        if($user_credit_file===false)
        {
            $field_array = array(
                "credit_identificationscanning"=>"idcardpassed",
                "credit_contact"=>"workpassed",
                "credit_credit"=>"creditpassed",
                "credit_incomeduty"=>"incomepassed",
                "credit_house"=>"housepassed",
                "credit_car"=>"carpassed",
                "credit_marriage"=>"marrypassed",
                "credit_titles"=>"skillpassed",
                "credit_videoauth"=>"videopassed",
                "credit_mobilereceipt"=>"mobiletruepassed",
                "credit_residence"=>"residencepassed",
                "credit_seal"=>"sealpassed",
            );

            if(!$user_info)
                $user_info =  get_user("*",$uid);

            $t_user_credit_file = $GLOBALS['db']->getAll("select uct.*,ucf.file,ucf.passed,ucf.passed_time,ucf.user_id from ".DB_PREFIX."user_credit_type uct LEFT JOIN ".DB_PREFIX."user_credit_file ucf  ON ucf.type=uct.type and ucf.user_id = ".intval($uid)." WHERE uct.is_effect =1  order by uct.sort ASC ");
            if($t_user_credit_file){
                foreach($t_user_credit_file as $k=>$v){
                    unset($v['brief']);
                    unset($v['description']);
                    if($user_info[$field_array[$v['type']]]){
                        if($user_info[$field_array[$v['type']]]>0){
                            $v['status'] = 0;
                        }
                        $v['passed'] = $user_info[$field_array[$v['type']]];
                        if($v['type']!="credit_seal")
                            $v['passed_time'] = $user_info[$field_array[$v['type']]."_time"];
                    }
                    //认证是否过期
                    $v['has_expire'] = 0;
                    if($v['expire'] > 0 && $v['status'] == 1){
                        if(TIME_UTC - $v['passed_time'] > $v['expire']*30*24*3600){
                            $v['has_expire'] = 1;
                        }
                    }

                    $user_credit_file[$v['type']] = $v;
                }
            }

            set_dynamic_cache($key,$user_credit_file);
        }
        $GLOBALS[$key] = $user_credit_file;
        return $GLOBALS[$key];
    }
}

/**
 * 获取用户的信息绑定资料
 */

function get_user_msg_conf($id){
    $key = md5("USER_MSG_CONF_".$id);
    if(isset($GLOBALS[$key]))
    {
        return $GLOBALS[$key];
    }
    else
    {
        $conf = load_dynamic_cache($key);
        if($conf===false)
        {
            $conf = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_conf where user_id = ".intval($id));
            set_dynamic_cache($key,$conf);
        }
        $GLOBALS[$key] = $conf;
        return $GLOBALS[$key];
    }
}

function get_message_rel_data($message,$field='name')
{
    return $GLOBALS['db']->getOne("select ".$field." from ".DB_PREFIX.$message['rel_table']." where id = ".intval($message['rel_id']));
}

function get_order_item_list($order_id)
{
    $deal_order_item = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."deal_order_item where order_id = ".$order_id);
    $str = '';
    foreach($deal_order_item as $k=>$v)
    {
        $str .="<br /><span title='".$v['name']."'>".msubstr($v['name'])."</span>[".$v['number']."]";
    }
    return $str;
}

//用于获取可同步登录的API
function get_api_login()
{
    if(trim($_REQUEST['act'])!='api_login')
    {
        $apis = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."api_login");
        $str = "<div class='blank'></div>";
        foreach($apis as $k=>$api)
        {
            $str .= $url."<span id='api_".$api['class_name']."_0'><script type='text/javascript'>load_api_url('".$api['class_name']."',0);</script></span>";
        }
        return $str;
    }
    else
        return '';
}

//获取已过时间
function pass_date($time)
{
    $time_span = TIME_UTC - $time;
    if($time_span>3600*24*365)
    {
        //一年以前
//			$time_span_lang = round($time_span/(3600*24*365)).$GLOBALS['lang']['SUPPLIER_YEAR'];
        //$time_span_lang = to_date($time,"Y".$GLOBALS['lang']['SUPPLIER_YEAR']."m".$GLOBALS['lang']['SUPPLIER_MON']."d".$GLOBALS['lang']['SUPPLIER_DAY']);
        $time_span_lang = to_date($time,"Y-m-d");
    }
    elseif($time_span>3600*24*30)
    {
        //一月
//			$time_span_lang = round($time_span/(3600*24*30)).$GLOBALS['lang']['SUPPLIER_MON'];
        //$time_span_lang = to_date($time,"Y".$GLOBALS['lang']['SUPPLIER_YEAR']."m".$GLOBALS['lang']['SUPPLIER_MON']."d".$GLOBALS['lang']['SUPPLIER_DAY']);
        $time_span_lang = to_date($time,"Y-m-d");
    }
    elseif($time_span>3600*24)
    {
        //一天
        //$time_span_lang = round($time_span/(3600*24)).$GLOBALS['lang']['SUPPLIER_DAY'];
        $time_span_lang = to_date($time,"Y-m-d");
    }
    elseif($time_span>3600)
    {
        //一小时
        $time_span_lang = round($time_span/(3600)).$GLOBALS['lang']['SUPPLIER_HOUR'];
    }
    elseif($time_span>60)
    {
        //一分
        $time_span_lang = round($time_span/(60)).$GLOBALS['lang']['SUPPLIER_MIN'];
    }
    else
    {
        //一秒
        $time_span_lang = $time_span.$GLOBALS['lang']['SUPPLIER_SEC'];
    }
    return $time_span_lang;
}



//获取用户的可用额度
function get_can_use_quota($uid){
    //用户的总额度
    if($uid!=$GLOBALS['user_info']['id'] && $uid > 0){
        $quota = get_user_info("quota","id = ".$uid,"ONE");
    }
    elseif($uid==$GLOBALS['user_info']['id'] && $uid > 0){
        $quota = $GLOBALS['user_info']['quota'];
    }
    //获取用户借款用去的额度
    $borrow_quota = $GLOBALS['db']->getOne("select sum(borrow_amount) from ".DB_PREFIX."deal where is_delete=0 AND publish_wait=0 AND deal_status in(0,1,2,4) AND type_id not in(select id FROM  ".DB_PREFIX."deal_loan_type WHERE is_quota=0) AND user_id = ".$uid);
    return ($quota->$borrow_quota);
}

// $type = middle,big,small

function show_avatar($u_id,$type="middle")
{
    $key = md5("AVATAR_".$u_id.$type);
    if(isset($GLOBALS[$key]))
    {
        return $GLOBALS[$key];
    }
    else
    {
        $avatar_key = md5("USER_AVATAR_".$u_id);
        $avatar_data = $GLOBALS['dynamic_avatar_cache'][$avatar_key];// 当前用户所有头像的动态缓存
        if(!isset($avatar_data)||!isset($avatar_data[$key]))
        {
            $avatar_file = get_user_avatar($u_id,$type);
            $avatar_str = "<a href='".url("index","space",array("id"=>$u_id))."' style='text-align:center; display:inline-block;'  onmouseover='userCard.load(this,".$u_id.");'>".
                "<img src='".$avatar_file."'  />".
                "</a>";
            $avatar_data[$key] = $avatar_str;
            if(count($GLOBALS['dynamic_avatar_cache'])<500) //保存500个用户头像缓存
            {
                $GLOBALS['dynamic_avatar_cache'][$avatar_key] = $avatar_data;
            }
        }
        else
        {
            $avatar_str = $avatar_data[$key];
        }
        $GLOBALS[$key]= $avatar_str;
        return $GLOBALS[$key];
    }
}

function update_avatar($u_id)
{
    $avatar_key = md5("AVATAR_".$u_id."middle");
    unset($GLOBALS['dynamic_avatar_cache'][$avatar_key]);
    $avatar_key = md5("AVATAR_".$u_id."big");
    unset($GLOBALS['dynamic_avatar_cache'][$avatar_key]);
    $avatar_key = md5("AVATAR_".$u_id."small");
    unset($GLOBALS['dynamic_avatar_cache'][$avatar_key]);
    $GLOBALS['cache']->set_dir(APP_ROOT_PATH."public/runtime/data/avatar_cache/");
    $GLOBALS['cache']->set("AVATAR_DYNAMIC_CACHE",$GLOBALS['dynamic_avatar_cache']); //头像的动态缓存
}


//获取用户头像的文件名
function get_user_avatar($id,$type)
{
    $uid = sprintf("%09d", $id);
    $dir1 = substr($uid, 0, 3);
    $dir2 = substr($uid, 3, 2);
    $dir3 = substr($uid, 5, 2);
    $path = $dir1.'/'.$dir2.'/'.$dir3;

    $id = str_pad($id, 2, "0", STR_PAD_LEFT);
    $id = substr($id,-2);
    $avatar_file = APP_ROOT."/public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    $avatar_check_file = APP_ROOT_PATH."public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    if(file_exists($avatar_check_file))
        return $avatar_file;
    else
        return  APP_ROOT."/public/avatar/noavatar_".$type.".gif";
}



function check_user_avatar($id,$type)
{
    $uid = sprintf("%09d", $id);
    $dir1 = substr($uid, 0, 3);
    $dir2 = substr($uid, 3, 2);
    $dir3 = substr($uid, 5, 2);
    $path = $dir1.'/'.$dir2.'/'.$dir3;

    $id = str_pad($id, 2, "0", STR_PAD_LEFT);
    $id = substr($id,-2);
    $avatar_file = APP_ROOT."/public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    $avatar_check_file = APP_ROOT_PATH."public/avatar/".$path."/".$id."virtual_avatar_".$type.".jpg";
    if(file_exists($avatar_check_file))
        return $avatar_file;
    else
        return false;
}

//添加一则日志
/**
 * @param $type			转发的类型标识    见下代码中的范围
 * @param $relay_id		转发的主题ID
 * @param $fav_id		喜欢主题的ID
 */
function insert_topic($type='', $fav_id = 0,$user_id = 0,$user_name = '',$l_user_id = 0)
{
    //定义类型的范围
    $type_array = array(
        "focus", //分享
        "transfer_message", //留言
        "deal_message", //留言
        "message", //留言
        "deal_message_reply", //回复
        "transfer_message_reply", //回复
        "message_reply",//回复
        "deal_collect",//关注FAV
    );
    if(!in_array($type,$type_array))
        return ;

    if($GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."topic WHERE `type`='$type' AND fav_id='$fav_id' AND user_id='$user_id' AND l_user_id='$l_user_id' ")==0){
        //添加
        $data['type'] = $type;
        $data['fav_id'] = $fav_id;
        $data['user_id'] = $user_id;
        $data['user_name'] = $user_name;
        $data['l_user_id'] = $l_user_id;
        $data['is_effect'] = 1;
        $data['create_time'] = TIME_UTC;
        $GLOBALS['db']->autoExecute(DB_PREFIX."topic",$data,"INSERT");
    }
}

function get_topic_list($limit,$condition='',$orderby='create_time desc',$keywords_array=array())
{
    if($orderby=='')$orderby='create_time desc';
    if($condition!='')
        $condition = " and ".$condition;
    $total = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."topic where is_effect = 1  ".$condition);
    $list = array();
    if($total > 0){
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."topic where is_effect = 1 ".$condition." order by ".$orderby." limit ".$limit);

        foreach($list as $k=>$v){
            if($v['type']=="deal_message" || $v['type']=="message" || $v['type']=="deal_message_reply" || $v['type']=="message_reply" || $v['type']=="deal_collect" || $v['type']=="deal_bad"){
                require_once(APP_ROOT_PATH."/app/Lib/deal.php");
                $list[$k]['deal'] = get_deal($v['fav_id']);
            }
            elseif($v['type']=="transfer_message" || $v['type']=="transfer_message_reply" ){
                require_once(APP_ROOT_PATH."/app/Lib/deal.php");
                $condition = ' AND dlt.id='.$v['fav_id'].' AND d.deal_status >= 4 and d.is_effect=1 and d.is_delete=0  and d.repay_time_type =1 and  d.publish_wait=0 ';
                $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id ";
                $list[$k]['transfer'] = get_transfer($union_sql,$condition);
            }
        }
    }

    return array('list'=>$list,'total'=>$total);
}


//获取相应规格的图片地址
//gen=0:保持比例缩放，不剪裁,如高为0，则保证宽度按比例缩放  gen=1：保证长宽，剪裁
function get_spec_image($img_path,$width=0,$height=0,$gen=0,$is_preview=true)
{
    //关于ALIOSS的生成
    if($GLOBALS['distribution_cfg']['OSS_TYPE']&&$GLOBALS['distribution_cfg']['OSS_TYPE']=="ALI_OSS")
    {
        $pathinfo = pathinfo($img_path);
        $file = $pathinfo['basename'];
        $dir = $pathinfo['dirname'];
        $dir = str_replace("./public/", "/public/", $dir);

        if($width==0)
        {
            $file_name = $GLOBALS['distribution_cfg']['OSS_DOMAIN'].$dir."/".$file;
        }
        else if($height==0)
        {
            $file_name = $GLOBALS['distribution_cfg']['OSS_DOMAIN'].$dir."/".$file."@".$width."w_1l_1x.jpg";
        }
        else if($gen==0)
            $file_name = $GLOBALS['distribution_cfg']['OSS_DOMAIN'].$dir."/".$file."@".$width."w_".$height."h_0c_1e_1x.jpg"; //以短边缩放 1e 不剪裁
        else
            $file_name = $GLOBALS['distribution_cfg']['OSS_DOMAIN'].$dir."/".$file."@".$width."w_".$height."h_1c_1e_1x.jpg"; //以短边缩放 1e 剪裁
        return $file_name;
    }

    if($width==0||substr($img_path, 0,2)!="./")
        $new_path = $img_path;
    else
    {
        //$img_name = substr($img_path,0,-4);
        //$img_ext = substr($img_path,-3);
        $fileinfo = pathinfo($img_path);
        $img_ext = $fileinfo['extension'];
        $len = strlen($img_ext) + 1;
        $img_name =substr($img_path,0,-$len);

        if($is_preview)
            $new_path = $img_name."_".$width."x".$height.".jpg";
        else
            $new_path = $img_name."o_".$width."x".$height.".jpg";
        if(!file_exists(APP_ROOT_PATH.$new_path))
        {
            require_once APP_ROOT_PATH."system/utils/es_imagecls.php";
            $imagec = new es_imagecls();
            $thumb = $imagec->thumb(APP_ROOT_PATH.$img_path,$width,$height,$gen,true,"",$is_preview);

            if($GLOBALS['distribution_cfg']['OSS_TYPE']&&$GLOBALS['distribution_cfg']['OSS_TYPE']=="ES_FILE")
            {
                $paths = pathinfo($new_path);
                $path = str_replace("./","",$paths['dirname']);
                $filename = $paths['basename'];
                $pathwithoupublic = str_replace("public/","",$path);

                $file_array['path'] = $pathwithoupublic;
                $file_array['file'] = get_domain().APP_ROOT."/".$path."/".$filename;
                $file_array['name'] = $filename;
                $GLOBALS['curl_param']['images'][] = $file_array;
            }

        }
    }
    //return APP_ROOT."/test.php?path=".$new_path."&rand=".rand(1000000,9999999);
    return $new_path;
}

function get_spec_gif_anmation($url,$width,$height)
{
    require_once APP_ROOT_PATH."system/utils/gif_encoder.php";
    require_once APP_ROOT_PATH."system/utils/gif_reader.php";
    require_once APP_ROOT_PATH."system/utils/es_imagecls.php";
    $gif = new GIFReader();
    $gif->load($url);
    $imagec = new es_imagecls();
    foreach($gif->IMGS['frames'] as $k=>$img)
    {
        $im = imagecreatefromstring($gif->getgif($k));
        $im = $imagec->make_thumb($im,$img['FrameWidth'],$img['FrameHeight'],"gif",$width,$height,$gen=1);
        ob_start();
        imagegif($im);
        $content = ob_get_contents();
        ob_end_clean();
        $frames [ ] = $content;
        $framed [ ] = $img['frameDelay'];
    }

    $gif_maker = new GIFEncoder (
        $frames,
        $framed,
        0,
        2,
        0, 0, 0,
        "bin"   //bin为二进制   url为地址
    );
    return $gif_maker->GetAnimation ( );
}

function load_comment_list()
{
    return $GLOBALS['tmpl']->fetch("inc/comment_list.html");
}
function load_message_list()
{
    return $GLOBALS['tmpl']->fetch("inc/message_list.html");
}
function load_reply_list()
{
    return $GLOBALS['tmpl']->fetch("inc/topic_page_reply_list.html");
}



//编译生成css文件
function parse_css($urls)
{

    $url = md5(implode(',',$urls));
    $css_url = 'public/runtime/statics/'.$url.'.css';
    $url_path = APP_ROOT_PATH.$css_url;
    if(!file_exists($url_path)||IS_DEBUG)
    {
        if(!file_exists(APP_ROOT_PATH.'public/runtime/statics/')){
            mkdir(APP_ROOT_PATH.'public/runtime/statics/');
            @chmod(APP_ROOT_PATH.'public/runtime/statics/', 0777);
        }

        $tmpl_path = $GLOBALS['tmpl']->_var['TMPL'];

        $css_content = '';
        foreach($urls as $url)
        {
            $css_content .= @file_get_contents($url);
        }
        $css_content = preg_replace("/[\r\n]/",'',$css_content);
        $css_content = str_replace("../images/",$tmpl_path."/images/",$css_content);
//		@file_put_contents($url_path, unicode_encode($css_content));
        @file_put_contents($url_path, $css_content);
    }
    return SITE_DOMAIN.APP_ROOT."/".$css_url;
}

/**
 *
 * @param $urls 载入的脚本
 * @param $encode_url 需加密的脚本
 */
function parse_script($urls,$encode_url=array())
{
    $url = md5(implode(',',$urls));
    $js_url = 'public/runtime/statics/'.$url.'.js';
    $url_path = APP_ROOT_PATH.$js_url;
    if(!file_exists($url_path)||IS_DEBUG)
    {
        if(!file_exists(APP_ROOT_PATH.'public/runtime/statics/')){
            mkdir(APP_ROOT_PATH.'public/runtime/statics/');
            @chmod(APP_ROOT_PATH.'public/runtime/statics/', 0777);
        }

        if(count($encode_url)>0)
        {
            require_once APP_ROOT_PATH."system/libs/javascriptpacker.php";
        }

        $js_content = '';
        foreach($urls as $url)
        {
            $append_content = @file_get_contents($url)."\r\n";
            if(in_array($url,$encode_url))
            {
                $packer = new JavaScriptPacker($append_content);
                $append_content = $packer->pack();
            }
            $js_content .= $append_content;
        }
//		require_once APP_ROOT_PATH."system/libs/javascriptpacker.php";
//	    $packer = new JavaScriptPacker($js_content);
//		$js_content = $packer->pack();
        @file_put_contents($url_path,$js_content);
    }
    return SITE_DOMAIN.APP_ROOT."/".$js_url;
}

//获取商城公告
function get_notice($limit=0)
{
    if($limit == 0)
        $limit = app_conf("INDEX_NOTICE_COUNT");
    if($limit>0)
    {
        $limit_str = "limit ".$limit;
    }
    else
    {
        $limit_str = "";
    }
    $list = $GLOBALS['db']->getAll("select a.*,ac.type_id from ".DB_PREFIX."article as a left join ".DB_PREFIX."article_cate as ac on a.cate_id = ac.id where ac.type_id = 2 and ac.is_effect = 1 and ac.is_delete = 0 and a.is_effect = 1 and a.is_delete = 0 order by a.sort desc ".$limit_str);

    foreach($list as $k=>$v)
    {
        if($v['type_id']==1)
        {
            $module = "help";
        }
        elseif($v['type_id']==2)
        {
            $module = "notice";
        }
        elseif($v['type_id']==3)
        {
            $module = "sys";
        }
        else
        {
            $module = 'article';
        }

        if($v['uname']!='')
            $aurl = url("index",$module,array("id"=>$v['uname']));
        else
            $aurl = url("index",$module,array("id"=>$v['id']));
        $list[$k]['url'] = $aurl;
    }
    return $list;
}

//获取指定的分类列表
function get_cate_tree($pid = 0,$is_all = 0)
{
    return load_auto_cache("cache_shop_cate_tree",array("pid"=>$pid,"is_all"=>$is_all));
}

//获取指定的文章分类列表
function get_acate_tree($pid = 0)
{
    return load_auto_cache("cache_shop_acate_tree",array("pid"=>$pid));
}

/**
 * 获取文章列表
 */
function get_article_list($limit, $cate_id=0, $where='',$orderby = '',$cached = true)
{
    $key = md5("ARTICLE".$limit.$cate_id.$where.$orderby);
    if($cached)
    {
        $res = $GLOBALS['cache']->get($key);
    }
    else
    {
        $res = false;
    }
    if($res===false)
    {

        $count_sql = "select count(*) from ".DB_PREFIX."article as a left join ".DB_PREFIX."article_cate as ac on a.cate_id = ac.id where a.is_effect = 1 and a.is_delete = 0 and ac.is_delete = 0 and ac.is_effect = 1 ";
        $sql = "select a.*,ac.type_id from ".DB_PREFIX."article as a left join ".DB_PREFIX."article_cate as ac on a.cate_id = ac.id where a.is_effect = 1 and a.is_delete = 0 and ac.is_delete = 0 and ac.is_effect = 1 ";

        if($cate_id>0)
        {
            $ids = load_auto_cache("deal_shop_acate_belone_ids",array("cate_id"=>$cate_id));
            $sql .= " and a.cate_id in (".implode(",",$ids).")";
            $count_sql .= " and a.cate_id in (".implode(",",$ids).")";
        }


        if($where != '')
        {
            $sql.=" and ".$where;
            $count_sql.=" and ".$where;
        }

        if($orderby=='')
            $sql.=" order by a.sort desc limit ".$limit;
        else
            $sql.=" order by ".$orderby." limit ".$limit;

        $articles_count = $GLOBALS['db']->getOne($count_sql);
        $articles = array();
        if($articles_count > 0){
            $articles = $GLOBALS['db']->getAll($sql);
            foreach($articles as $k=>$v)
            {
                if($v['type_id']==1)
                {
                    $module = "help";
                }
                elseif($v['type_id']==2)
                {
                    $module = "notice";
                }
                elseif($v['type_id']==3)
                {
                    $module = "sys";
                }
                else
                {
                    $module = 'article';
                }

                if($v['uname']!='')
                    $aurl = url("index",$module,array("id"=>$v['uname']));
                else
                    $aurl = url("index",$module,array("id"=>$v['id']));

                $articles[$k]['url'] = $aurl;
            }
        }



        $res = array('list'=>$articles,'count'=>$articles_count);
        $GLOBALS['cache']->set($key,$res);
    }
    return $res;
}

function load_page_png($img)
{
    return load_auto_cache("page_image",array("img"=>$img));
}

function get_article($id)
{
    return $GLOBALS['db']->getRow("select a.*,ac.type_id from ".DB_PREFIX."article as a left join ".DB_PREFIX."article_cate as ac on a.cate_id = ac.id where a.id = ".intval($id)." and a.is_effect = 1 and a.is_delete = 0");
}
function get_article_buy_uname($uname)
{
    return $GLOBALS['db']->getRow("select a.*,ac.type_id from ".DB_PREFIX."article as a left join ".DB_PREFIX."article_cate as ac on a.cate_id = ac.id where a.uname = '".addslashes($uname)."' and a.is_effect = 1 and a.is_delete = 0");
}



function show_ke_image($id,$cnt="")
{
    if($cnt)
    {
        $image_path = $cnt;
        $is_show="display:inline-block;";
    }
    else{
        $image_path =APP_ROOT."/admin/Tpl/default/Common/images/no_pic.gif";
        $is_show="display:none;";
    }

    $parseStr= "<span>
        <div style='float:left; height:35px; padding-top:1px;'>
			<input type='hidden' value='".(empty($cnt) ? "" : $image_path)."' name='$id' id='keimg_h_$id' />
			<div class='buttonActive' style='margin-right:5px;'>
				<div class='buttonContent'>
					<button type='button' class='keimg ke-icon-upload_image' rel='$id'>选择图片</button>
				</div>
			</div>
		</div>
		 <a href='$image_path' target='_blank' id='keimg_a_$id' ><img src='$image_path' id='keimg_m_$id' width=35 height=35 style='float:left; border:#ccc solid 1px; margin-left:5px;' /></a>
		 <div style='float:left; height:35px; padding-top:1px;margin-right:10px'>
			 <div class='buttonActive'>
				<div class='buttonContent'>
					<img src='".APP_ROOT."/admin/Tpl/default/Common/images/del.gif' style='$is_show; margin-left:10px; float:left; border:#ccc solid 1px; width:35px; height:35px; cursor:pointer;' class='keimg_d' rel='$id' title='删除'>
				</div>
			</div>
		</div>
		</span>";
    return $parseStr;
}

function show_ke_textarea($id,$width=630,$height=350,$cnt="")
{
    return "<div  style='margin-bottom:5px; '><textarea id='".$id."' name='".$id."' class='ketext' style='width:".$width."px; height:".$height."px;' >".$cnt."</textarea> </div>";
}

function replace_public($content)
{
    $domain = app_conf("PUBLIC_DOMAIN_ROOT")==''?SITE_DOMAIN.APP_ROOT:app_conf("PUBLIC_DOMAIN_ROOT");
    $domain_origin = SITE_DOMAIN.APP_ROOT;
    $content = str_replace($domain."/public/","./public/",$content);
    $content = str_replace($domain_origin."/public/","./public/",$content);
    return $content;
}

function check_user_auth($m_name,$a_name,$rel_id)
{
    $rs = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_auth where m_name = '".$m_name."' and a_name = '".$a_name."' and user_id = ".intval($GLOBALS['user_info']['id']));
    foreach($rs as $row)
    {
        if($row['rel_id']==0||$row['rel_id']==$rel_id)
        {
            return true;
        }
    }
    return false;
}

function get_user_auth()
{
    $user_auth = array();
    //定义用户权限
    $user_auth_rs = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_auth where user_id = ".intval($GLOBALS['user_info']['id']));
    foreach($user_auth_rs as $k=>$row)
    {
        $user_auth[$row['m_name']][$row['a_name']][$row['rel_id']] = true;
    }
    return $user_auth;
}


function get_op_change_show($m_name,$a_name)
{
    if($a_name=="replydel"||$a_name=='del')
    {
        //删除
        $money = doubleval(app_conf("USER_DELETE_MONEY"));
        $money_f = "-".format_price(0-$money);
        $score = intval(app_conf("USER_DELETE_SCORE"));
        $score_f = "-".format_score(0-$score);
        $point = intval(app_conf("USER_DELETE_POINT"));
        $point_f = "-".(0-$point)."经验";
    }
    else
    {
        //增加
        $money = doubleval(app_conf("USER_ADD_MONEY"));
        $money_f = "+".format_price($money);
        $score = intval(app_conf("USER_ADD_SCORE"));
        $score_f = "+".format_score($score);
        $point = intval(app_conf("USER_ADD_POINT"));
        $point_f = "+".$point."经验";
    }
    $str = "";
    if($money!=0)$str .= $money_f;
    if($score!=0)$str .= $score_f;
    if($point!=0)$str .= $point_f;
    return $str;

}

function get_op_change($m_name,$a_name)
{
    if($a_name=="replydel"||$a_name=='del')
    {
        //删除
        $money = doubleval(app_conf("USER_DELETE_MONEY"));

        $score = intval(app_conf("USER_DELETE_SCORE"));

        $point = intval(app_conf("USER_DELETE_POINT"));

    }
    else
    {
        //增加
        $money = doubleval(app_conf("USER_ADD_MONEY"));

        $score = intval(app_conf("USER_ADD_SCORE"));

        $point = intval(app_conf("USER_ADD_POINT"));

    }
    return array("money"=>$money,"score"=>$score,"point"=>$point);

}

function show_topic_form($text_name,$width="300px",$height="80px",$is_img = false,$is_topic = false,$is_event = false,$id="topic_form_textarea",$show_btn=false,$show_tag=false)
{

    $GLOBALS['tmpl']->caching = true;
    $cache_id  = md5("show_topic_form".$text_name.$width.$height.$is_img.$is_topic.$is_event.$id.$show_btn);
    if (!$GLOBALS['tmpl']->is_cached('inc/topic_form.html', $cache_id))
    {
        $GLOBALS['tmpl']->assign("text_name",$text_name);
        //输出表情数据html
        $result = $GLOBALS['db']->getAll("select `type`,`title`,`emotion`,`filename` from ".DB_PREFIX."expression order by type");
        $expression = array();
        foreach($result as $k=>$v)
        {
            $v['filename'] = "./public/expression/".$v['type']."/".$v['filename'];
            $v['emotion'] = str_replace(array('[',']'),array('',''),$v['emotion']);
            $expression[$v['type']][] = $v;
        }

        $tag_list =$GLOBALS['db']->getAll("select name from ".DB_PREFIX."topic_tag where is_preset = 1 order by count desc limit 5");

        $GLOBALS['tmpl']->assign("tag_list",$tag_list);
        $GLOBALS['tmpl']->assign("expression",$expression);
        $GLOBALS['tmpl']->assign("is_img",$is_img);
        $GLOBALS['tmpl']->assign("width",$width);
        $GLOBALS['tmpl']->assign("height",$height);
        $GLOBALS['tmpl']->assign("is_event",$is_event);
        if($is_event)
        {
            $fetch_list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."fetch_topic where is_effect = 1 order by sort desc");
            $GLOBALS['tmpl']->assign("fetch_list",$fetch_list);
        }
        $GLOBALS['tmpl']->assign("is_topic",$is_topic);
        $GLOBALS['tmpl']->assign("box_id",$id);
        $GLOBALS['tmpl']->assign("show_btn",$show_btn);
        $GLOBALS['tmpl']->assign("show_tag",$show_tag);
    }
    return $GLOBALS['tmpl']->fetch("inc/topic_form.html",$cache_id);
}

function get_gopreview()
{
    $gopreview = es_session::get("gopreview");
    if(!isset($gopreview)||$gopreview=="")
    {
        $gopreview = es_session::get('before_login')?es_session::get('before_login'):url("index");
    }
    es_session::delete("before_login");
    es_session::delete("gopreview");
    return $gopreview;
}

function set_gopreview()
{
    $url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?");
    $parse = parse_url($url);
    if(isset($parse['query'])) {
        parse_str($parse['query'],$params);
        $url   =  $parse['path'].'?'.http_build_query($params);
    }
    if(app_conf("URL_MODEL")==1)$url = $GLOBALS['current_url'];
    es_session::set("gopreview",$url);
}

function app_recirect_preview()
{
    app_redirect(get_gopreview());
}


/**
 * 剩余时间
 */
function remain_time($remain_time){
    $d = intval($remain_time/86400);
    $h = intval(($remain_time%86400)/3600);
    $m = intval(($remain_time%3600)/60);
    return $d.$GLOBALS['lang']['DAY'].$h.$GLOBALS['lang']['HOUR'].$m.$GLOBALS['lang']['MIN'];
}


/**
 * 技术两个日期差几个月
 */
function how_much_month($start_time,$end_time){
    if($start_time=="" || $end_time=="")
    {
        return "";
    }
    $time1 = to_date($start_time,"Y")*12 + to_date($start_time,"m");
    $time2 = to_date($end_time,"Y")*12 + to_date($end_time,"m");
    return $time2 - $time1;
}

function gen_qrcode($str,$size = 5,$img=false)
{
    require_once APP_ROOT_PATH."system/phpqrcode/qrlib.php";

    if($img)
    {
        QRcode::png($str, false, 'Q', $size, 2);
        return;
    }

    $root_dir = APP_ROOT_PATH."public/images/qrcode";
    if (!is_dir($root_dir)) {
        @mkdir($root_dir);
        @chmod($root_dir, 0777);
    }

    $filename = md5($str."|".$size);
    $hash_dir = $root_dir. '/c' . substr(md5($filename), 0, 12)."/";

    if (!is_dir($hash_dir))
    {
        @mkdir($hash_dir);
        @chmod($hash_dir, 0777);
    }

    $filesave = $hash_dir.$filename.'.png';

    $fileurl =  "./public/images/qrcode/c". substr(md5($filename), 0, 12)."/".$filename.".png";
    if(!file_exists($filesave))
    {
        QRcode::png($str, $filesave, 'Q', $size, 2);
        $QR =  APP_ROOT_PATH.$fileurl;
        $logo = app_conf("QRCODE_LOGO");

        if($logo !== "")
        {
            $logo = APP_ROOT_PATH.$logo;
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);
            $QR_height = imagesy($QR);
            $logo_width = imagesx($logo);
            $logo_height = imagesy($logo);
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            imagepng($QR,APP_ROOT_PATH.$fileurl);
        }

        if($GLOBALS['distribution_cfg']['OSS_TYPE']&&$GLOBALS['distribution_cfg']['OSS_TYPE']!="NONE")
            syn_to_remote_image_server($fileurl);
    }
    return $fileurl;
}


//显示成功
function showIpsInfo($msg,$jump='')
{
    echo $msg;
    $return['msg'] = $msg ;
    $return['status'] = 1 ;
    $return['jump'] = $jump ;
    ajax_return($return);
    //$GLOBALS['tmpl']->assign('msg',$msg);
    if($jump)
    {
        //$GLOBALS['tmpl']->assign('jump',);
    }
    else
    {
        //$jump =  $_SERVER['HTTP_REFERER'];
        $jump = APP_ROOT."/";
    }
    //$GLOBALS['tmpl']->assign('jump',$jump);
    //$GLOBALS['tmpl']->display("ips_show.html");
    exit;
}


/**
 * 商户端获取银行列表查询(WS)
 * @return
 * 		  pErrCode 4 返回状态 否 0000成功； 9999失败；
 * 		  pErrMsg 100 返回信息 否 状态0000：成功 除此乊外：反馈实际原因
 * 		  pBankList 银行名称|银行卡别名|银行卡编号#银行名称|银行卡别名|银行卡编号
 * 		  BankList[] = array('name'=>银行名称,'sub_name'=>银行卡别名,'id'=>银行卡编号);
 */
function GetIpsBankList(){

    //$result = $GLOBALS['cache']->get("IPS_BANK_LIST");
    //if($result===false){
    $class_name = getCollName();
    //$ips_file = APP_ROOT_PATH."system/collocation/".$class_name."_collocation.php";
    //require_once $ips_file;
    //$collocation_class = $class_name."_collocation";
    //$collocation_object = new $collocation_class();
    //$result = $collocation_object->GetBankList();
    //if(count($result['BankList']) > 0)
    //	$GLOBALS['cache']->set("IPS_BANK_LIST",$result);
    //}
    //print_r($result);

    return $result;
}

/**
 * 获得用户余额
 * @param int $user_id
 * @param int $user_type
 * @return
 * 	 * 			pMerCode 6 “平台”账号 否 由IPS颁发的商户号
pErrCode 4 返回状态 否 0000成功； 9999失败；
pErrMsg 100 返回信息 否 状态0000：成功 除此乊外：反馈实际原因
pIpsAcctNo 30 IPS账户号 否 查询时提交
pBalance 10 可用余额 否 带正负符号，带小数点，最多保留两位小数
pLock 10 冻结余额 否 带正负符号，带小数点，最多保留两位小数
pNeedstl 10 未结算余额 否 带正负符号，带小数点，最多保留两位小数
 */
function GetIpsUserMoney($user_id,$user_type = 0){
    if(intval(app_conf("OPEN_IPS")) > 0){
        $class_name = getCollName();
        require_once APP_ROOT_PATH."system/collocation/".$class_name."_collocation.php";
        $collocation_class = $class_name."_collocation";
        $collocation_object = new $collocation_class();
        $result = $collocation_object->QueryForAccBalance($user_id,$user_type);

        return $result;
    }
    else{

        return false;
    }
}



//更改过期流标状态
function change_deal_status(){
    //$sql = "select id from ".DB_PREFIX."deal where is_effect = 1 and deal_status = 1 and is_delete = 0 AND load_money/borrow_amount < 1 AND (start_time + enddate*24*3600 - ".TIME_UTC.") <=0  ";
    /*$sql = "select id from ".DB_PREFIX."deal where is_effect = 1 and deal_status = 1 and is_delete = 0 AND load_money/borrow_amount <= 1 ";
     $deal_ids = $GLOBALS['db']->getAll($sql);

    foreach($deal_ids as $k=>$v)
    {
    syn_deal_status($v['id']);
    }*/
    syn_dealing();
}

/**
 * 获得提现手续费
 * @param float $money  提现金额
 * @param user $user_info 用户信息
 * @return float 提现手续费
 */
function getCarryFee($money,$user_info){
    $fee = 0;
    $feel_type = 0;
    //获取手续费配置表
    $vip_id = 0;
    if($user_info['vip_id'] > 0 && $user_info['vip_state'] == 1){
        $vip_id = $user_info['vip_id'];
    }

    //手续费
    $fee_config = load_auto_cache("user_carry_config",array("vip_id"=>$vip_id));
    //如果手续费大于最大的配置那么取这个手续费
    if($money >=$fee_config[count($fee_config)-1]['max_price']){
        $fee = $fee_config[count($fee_config)-1]['fee'];
        $feel_type = $fee_config[count($fee_config)-1]['fee_type'];
    }
    else{
        foreach($fee_config as $k=>$v){
            if($money >= $v['min_price'] && $money <= $v['max_price']){
                $fee =  floatval($v['fee']);
                $feel_type = $v['fee_type'];
            }
        }
    }

    if($feel_type == 1){
        $fee = $money * $fee * 0.01;
    }

    return $fee;
}

/**
 * 获取VIP等级名称
 */
function get_vip_name($vip_id){
    if($vip_id==0)
        return "";
    $vip = load_auto_cache("vip_list",array("id"=>$vip_id));
    return $vip[$vip_id]['vip_grade'];
}
function format_conf_count($num , $int_number){
    return $num;
}
/**
 * 查询某件商品信息及用户可购买数量
 * @param 商品编号 $id
 * @param 会员编号 $user_id
 */
function get_goods_info($id,$user_id)
{
    $id = intval($id);
    $user_id = intval($user_id);
    $sql = "SELECT g.*,gc.name as cate_name from ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."goods_cate gc ON g.cate_id = gc.id where g.id = ".$id ;
    $goods = $GLOBALS['db']->getRow($sql);

    $goods['max_bought_format'] = $goods['max_bought'] - $goods['buy_number'];

    //如果有限制购买数量
    if($goods['user_max_bought'] > 0 ){
        $goods['user_can_buy_number'] = $goods['user_max_bought'];
        if($GLOBALS['user_info']){
            //登陆后 用户可购买数=库存数-当月已购买数量
            $goods['user_can_buy_number'] = $goods['user_max_bought'] - $GLOBALS['db']->getOne("SELECT sum(number) from ".DB_PREFIX."goods_order WHERE date_format(ex_date,'%Y-%m')=date_format(now(),'%Y-%m') and goods_id=".$id." AND user_id=".$user_id);
            if($goods['user_can_buy_number'] > $goods['max_bought_format']){
                $goods['user_can_buy_number'] = $goods['max_bought_format'];
            }
        }
    }
    else{
        $goods['user_can_buy_number'] = $goods['max_bought_format'];
    }


    return $goods;
}

/**
 * 查询某件商品的商品属性及库存
 * @param 商品编号 $id
 * @param 商品类型编号 $goods_type_id
 */
function get_goods_attr($goods_type_id,$id)
{
    $has_stock = 0;
    $goods_type_attr = $GLOBALS['db']->getAll("select id,name from ".DB_PREFIX."goods_type_attr where  goods_type_id = ".$goods_type_id,false);
    $tmp_goods_attr =  $GLOBALS['db']->getAll("select * from ".DB_PREFIX."goods_attr where  goods_id = ".$id);
    $goods_attr= array();
    foreach($tmp_goods_attr as $k=>$v){
        $goods_attr[$v['goods_type_attr_id']][] = $v;
    }

    foreach ($goods_type_attr as $k=>$v)
    {
        if(!$goods_attr[$v['id']]){
            unset($goods_type_attr[$k]);
        }
        else{
            $goods_type_attr[$k]['list'] = $goods_attr[$v['id']];
            foreach ($goods_type_attr[$k]['list'] as $kk=>$vv)
            {
                $goods_type_attr[$k]['list'][$kk]['score']=intval($vv['score']);
                if(intval($vv['is_checked']) == 1){
                    $has_stock = 1;
                }
            }
        }
    }

    if($has_stock == 1){
        //库存
        $attr_stock = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."goods_attr_stock where  goods_id = ".$id);
        foreach($attr_stock as $k=>$v){
            $attr_stock[$k]['attr_cfg'] = unserialize($v['attr_cfg']);
        }
    }
    $result['goods_type_attr'] = $goods_type_attr;  //商品属性
    $result['has_stock'] = $has_stock; //是否有库存
    $result['attr_stock'] = $attr_stock;  //某种属性类型的库存
    return $result;
}

/**
 * 判断是否有该属性库存
 */
function get_attr_stock($goods,$number,$goods_id,$attr)
{
    $goods_attr_scoresum = 0;
    $attr_str = "";
    //判断是否选择了属性
    if($goods['goods_type_id'] > 0){
        $goods_attr =  $GLOBALS['db']->getAll("select * from ".DB_PREFIX."goods_attr where  goods_id = ".$goods_id);

        if($goods_attr && !$attr){
            $result['info']="请选择属性";
            $result['status'] = 0;
            return $result;
        }

        //库存
        $attr_stock = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."goods_attr_stock where  goods_id = ".$goods_id);
        $temp_attr_stock = array();
        foreach($attr_stock as $k=>$v){
            $temp_attr_stock[$v['attr_str']] = $v;
        }

        $temp_attr_list = $GLOBALS['db']->getAll("select *  from ".DB_PREFIX."goods_attr where  goods_id = ".$goods_id);

        //用户所选择的该商品的属性列表
        $attr_list = array();
        foreach($temp_attr_list as $k=>$v){
            $attr_list[$v['goods_type_attr_id']][$v['id']] = $v;
        }
        foreach($attr as $k=>$v){
            $attr_str .= $attr_list[$k][$v]['name'];
            $goods_attr_scoresum +=$attr_list[$k][$v]['score'];
        }


        if(isset($temp_attr_stock[$attr_str])){
            if($number > (intval($temp_attr_stock[$attr_str]['stock_cfg']) - intval($temp_attr_stock[$attr_str]['buy_count']))){
                $result['info']="该商品属性库存不足，无法兑换，请重新选择";
                $result['status'] = 0;
                return $result;
            }
        }

        $result['status'] = 1;
        $result['temp_attr_stock'] = $temp_attr_stock;
        $result['attr_str'] = $attr_str;
        $result['goods_attr_scoresum'] = $goods_attr_scoresum;

    }
    elseif($number > $goods['max_bought_format']){
        $result['info']="库存不足";
        $result['status'] = 0;

    }
    //return $result;
    return $result;
}

/**
 * 获取订单列表
 */
function get_order($limit,$user_id,$condition){
    $count_sql = "SELECT count(*) from ".DB_PREFIX."goods_order go where $condition and go.user_id = ".$user_id;
    $count = $GLOBALS['db']->getOne($count_sql);

    if($count > 0){
        $sql = "SELECT go.* from ".DB_PREFIX."goods_order go where $condition and go.user_id = ".$user_id."  order by go.id  DESC LIMIT ".$limit;

        $order_info = $GLOBALS['db']->getAll($sql);
        $attr_str = "";
        foreach($order_info as $k=>$v){
            $order_info[$k]['attr_format'] = unserialize($v['attr']);
            foreach($order_info[$k]['attr_format'] as $kk=>$vv){
                $attr_str .= $GLOBALS['db']->getOne("select name from ".DB_PREFIX."goods_type_attr where id =".$kk );
                $attr_str .=":";
                $attr_str .= $GLOBALS['db']->getOne("select name from ".DB_PREFIX."goods_attr where id =".$vv );
                $attr_str .="  ";
            }
            $order_info[$k]['attr_format'] = $attr_str;
            $attr_str = "";
            if($order_info[$k]['is_delivery'] == 0)
            {	$order_info[$k]['is_delivery_format'] = "否";}
            else{
                $order_info[$k]['is_delivery_format'] = "是";
            }
            if($order_info[$k]['order_status'] == 0){
                $order_info[$k]['order_status_format'] = "未发货";
            }elseif($order_info[$k]['order_status'] == 1){
                $order_info[$k]['order_status_format'] = "已发货";
            }elseif($order_info[$k]['order_status'] == 2){
                $order_info[$k]['order_status_format'] = "无效订单";
            }elseif($order_info[$k]['order_status'] == 3){
                $order_info[$k]['order_status_format'] = "用户取消";
            }


            $a=get_goods($order_info[$k]['goods_id']);
            $order_info[$k]['img'] = $a['img'];
            $order_info[$k]['ex_time'] = to_date( $v['ex_time'],"Y-m-d H:i:s");
            $order_info[$k]['delivery_time'] = to_date( $v['delivery_time'],"Y-m-d H:i:s");
        }
    }

    return array("list"=>$order_info,'count'=>$count);
}

function get_abs_img_root($content)
{

    //return str_replace("./public/",APP_ROOT."public/",$content);
    //return str_replace('/mapi/','/',$str);
    return $content;
}
/**
 * 获取网站统计
 */
function site_statics(){

    //$stats = $GLOBALS['cache']->get("site_statics");
    if($stats==false){

        //累计投资金额
        $load_rs = $GLOBALS['db']->getRow("SELECT sum(money) as total_load,count(*) as load_count FROM ".DB_PREFIX."deal_load where is_repay= 0 ");
        $stats['total_load'] = $load_rs['total_load'] ;// + floatval(trim(app_conf("VIRTUAL_MONEY_1")));
        $stats['load_count'] = $load_rs['load_count'];
        $stats['total_load_format'] = format_conf_count(number_format($stats['total_load'],2));
        //成交笔数
        $stats['deal_total_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal where  deal_status >=4 ");


        //累计创造收益
        $stats['total_rate'] = $GLOBALS['db']->getOne("SELECT sum(true_interest_money + impose_money + true_reward_money - true_manage_money - true_manage_interest_money) FROM ".DB_PREFIX."deal_load_repay where  has_repay = 1 ");

        $stats['total_rate'] += $GLOBALS['db']->getOne("SELECT sum(rebate_money) FROM ".DB_PREFIX."deal_load where  is_has_loans = 1 ");//加上返利
        $stats['total_rate'] -= $GLOBALS['db']->getOne("SELECT sum(fee_amount) FROM ".DB_PREFIX."payment_notice WHERE  is_paid =1  "); //减去充值手续费
        $stats['total_rate'] -= $GLOBALS['db']->getOne("SELECT sum(fee) FROM ".DB_PREFIX."user_carry WHERE status =1  "); //减去提现手续费
        $stats['total_rate'] += $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."referrals WHERE pay_time >0  "); //加上邀请返利

        //$stats['total_rate'] += floatval(trim(app_conf("VIRTUAL_MONEY_2")));
        //var_dump($stats['total_rate']);exit;
        $stats['total_rate_format'] = format_conf_count(number_format($stats['total_rate'],2));
        //本息保证金（元）
        $stats['total_bzh'] = $GLOBALS['db']->getOne("SELECT sum(guarantor_real_freezen_amt+real_freezen_amt) FROM ".DB_PREFIX."deal where deal_status= 4 ");
        //$stats['total_bzh'] += floatval(trim(app_conf("VIRTUAL_MONEY_3")));
        $stats['total_bzh_format'] = format_conf_count(number_format($stats['total_bzh'],2));
        //待收资金（元）
        $stats['total_repay'] = $GLOBALS['db']->getOne("SELECT sum(repay_money) FROM ".DB_PREFIX."deal_load_repay where has_repay = 1 ");
        $stats['total_repay_format'] = format_conf_count(number_format($stats['total_repay'],2));
        //待投资金（元）
        $statsU = $GLOBALS['db']->getRow("SELECT sum(AES_DECRYPT(money_encrypt,'".AES_DECRYPT_KEY."')) as total_usermoney ,count(*) total_user FROM ".DB_PREFIX."user where is_effect = 1 and is_delete=0 ");
        $stats['total_usermoney'] = $statsU['total_usermoney'];
        $stats['total_usermoney_format'] = format_conf_count(number_format($stats['total_usermoney'],2));
        $stats['total_user'] = $statsU['total_user'];

        //注册人数
        $stats['user_count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."user where is_effect = 1 and user_type in(0,1)");

        //回款金额
        $stats['total_repay_money'] =  $GLOBALS['db']->getOne("SELECT sum(true_repay_money) FROM ".DB_PREFIX."deal_repay where has_repay = 1 ");
        $stats['total_repay_money_format'] = format_conf_count($stats['total_repay_money']);

        //$GLOBALS['cache']->set("site_statics",$stats);
    }

    return $stats;
}

/**
 * 获取最近的投资列表
 */
function  get_near_deal_loads($limit="0,10"){
    $list = $GLOBALS['db']->getAll("SELECT dl.*,d.name,d.rate FROM ".DB_PREFIX."deal_load dl LEFT JOIN ".DB_PREFIX."deal d ON d.id = dl.deal_id  order by id DESC LIMIT ".$limit);
    return $list;
}

/**
 * 签到奖励
 */
function signin($user_id){
    $t_begin_time = to_timespan(to_date(TIME_UTC,"Y-m-d"));  //今天开始
    $t_end_time = to_timespan(to_date(TIME_UTC,"Y-m-d"))+ (24*3600 - 1);  //今天结束
    $y_begin_time = $t_begin_time - (24*3600); //昨天开始
    $y_end_time = $t_end_time - (24*3600);  //昨天结束

    $t_sign_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_sign_log where user_id = ".$user_id." and sign_date between ".$t_begin_time." and ".$t_end_time);
    if($t_sign_data)
    {
        $result['status'] = 1;
        $result['info'] = "您已经签到过了";
    }
    else
    {
        $y_sign_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_sign_log where user_id = ".$user_id." and sign_date between ".$y_begin_time." and ".$y_end_time);
        $total_signcount = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_sign_log where user_id = ".$user_id);
        if($y_sign_data&&$total_signcount>=3)
        {
            $point = intval(app_conf("USER_LOGIN_KEEP_POINT"));
            $score = intval(app_conf("USER_LOGIN_KEEP_SCORE"));
            $nmc_money = intval(app_conf("USER_LOGIN_KEEP_NMC_MONEY"));

            if(app_conf("USER_LOGIN_KEEP_MONEY_TYPE") == 0)
                $money = floatval(app_conf("USER_LOGIN_KEEP_MONEY"));
            else{
                $money = 0;
                $money_list = unserialize(app_conf("USER_LOGIN_KEEP_MONEY"));
                foreach($money_list as $kk=>$vv){
                    if($GLOBALS['user_info']['money'] >=$vv['minprice']){
                        if($GLOBALS['user_info']['money'] <=$vv['maxprice'])
                        {
                            if($vv['type']==0)
                                $money = floatval($vv['money']);
                            else
                                $money = $GLOBALS['user_info']['money']*0.01*floatval($vv['money']);

                        }
                        elseif($GLOBALS['user_info']['money'] > $vv['maxprice']){
                            if($vv['type']==0)
                                $money = floatval($vv['money']);
                            else
                                $money = $GLOBALS['user_info']['money']*0.01*floatval($vv['money']);

                        }
                    }
                }
            }
        }
        else
        {
            $point = intval(app_conf("USER_LOGIN_POINT"));
            $score = intval(app_conf("USER_LOGIN_SCORE"));
            $nmc_money = intval(app_conf("USER_LOGIN_NMC_MONEY"));
            if(app_conf("USER_LOGIN_MONEY_TYPE") == 0)
                $money = floatval(app_conf("USER_LOGIN_MONEY"));
            else{
                $money = 0;
                $money_list = unserialize(app_conf("USER_LOGIN_MONEY"));
                foreach($money_list as $kk=>$vv){
                    if($GLOBALS['user_info']['money'] >=$vv['minprice']){
                        if($GLOBALS['user_info']['money'] <=$vv['maxprice'])
                        {
                            if($vv['type']==0)
                                $money = floatval($vv['money']);
                            else
                                $money = $GLOBALS['user_info']['money']*0.01*floatval($vv['money']);

                        }
                        elseif($GLOBALS['user_info']['money'] > $vv['maxprice']){
                            if($vv['type']==0)
                                $money = floatval($vv['money']);
                            else
                                $money = $GLOBALS['user_info']['money']*0.01*floatval($vv['money']);


                        }
                    }
                }
            }
        }
        if($point>0||$score>0||$money>0||$nmc_money>0)
        {
            require_once APP_ROOT_PATH."system/libs/user.php";
            if($money>0)
                $data["money"]=$money;
            if($score>0)
                $data["score"]=$score;
            if($point>0)
                $data["point"]=$point;

            if($nmc_money == 0)
                modify_account($data,$user_id,"您在".to_date(TIME_UTC)."签到成功",25);
            else{
                modify_account($data,$user_id,"您在".to_date(TIME_UTC)."签到成功",25);
                $data = "";
                $data["money"]=$nmc_money;
                $data["nmc_amount"]=$nmc_money;
                modify_account($data,$user_id,"您在".to_date(TIME_UTC)."签到成功",25);
            }



            $sign_log['user_id'] = $user_id;
            $sign_log['sign_date'] = TIME_UTC;
            $GLOBALS['db']->autoExecute(DB_PREFIX."user_sign_log",$sign_log);
        }



        $result['status'] = 1;
        $result['info'] = "签到成功";
    }

    return $result;
}

/**
 * 按宽度格式化html内容中的图片
 * @param unknown_type $content
 * @param unknown_type $width
 * @param unknown_type $height
 */
function format_html_content_image($content,$width,$height=0)
{
    $res = preg_match_all("/<img.*?src=[\"|\']([^\"|\']*)[\"|\'][^>]*>/i", $content, $matches);

    if($res)
    {
        foreach($matches[0] as $k=>$match)
        {
            $old_path = $matches[1][$k];
            $s_old_path = str_replace(SITE_DOMAIN,".",$old_path);
            if(preg_match("/\.\/public\//i", $s_old_path))
            {
                $new_path = get_spec_image($s_old_path,$width,$height,0);
                $content = str_replace($match, "<img src='".$new_path."' />", $content);
            }
        }
    }

    return $content;
}

/**
 * 按宽度格式化html内容中的图片
 * @param unknown_type $content
 */
function format_html_content_image1($content)
{
    $res = preg_match_all("/<img.*?src=[\"|\']([^\"|\']*)[\"|\'][^>]*>/i", $content, $matches);

    if($res)
    {
        foreach($matches[0] as $k=>$match)
        {
            $old_path = $matches[1][$k];
            $s_old_path = str_replace(SITE_DOMAIN,".",$old_path);
            if(preg_match("/\.\/public\//i", $s_old_path))
            {
                $content = str_replace($match, "<img src='".$s_old_path."' width='98%' />", $content);
            }
        }
    }

    return $content;
}

/**
 * 获取指定的投标
 */
function get_deal($id=0,$is_effect=1)
{
    $time = TIME_UTC;

    if($is_effect == 1)
    {
        //$ext = " and is_effect = 1 ";
    }
    if($id==0)  //有ID时不自动获取
    {
        return false;
        /*$sql = "select id from ".DB_PREFIX."deal where is_effect = 1 and is_delete = 0  ";
            if($cate_id>0)
            {

        $ids =load_auto_cache("deal_sub_parent_cate_ids",array("cate_id"=>$cate_id));

        $sql .= " and cate_id in (".implode(",",$ids).")";
        }

        $sql.=" order by sort desc";
        $deal = $GLOBALS['db']->getRow($sql);
        */

    }
    else{
        $deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".intval($id)."  and is_delete <> 1  $ext");
    }

    if($deal)
    {
        if($deal['deal_status']!=3 && $deal['deal_status']!=5)
        {
            $temp_data =syn_deal_status($deal['id']);
            $deal = array_merge($deal,$temp_data);
        }
        format_deal_item($deal);

    }
    return $deal;

}


/**
 * 获取正在进行的投标列表
 */
function get_deal_list($limit="",$cate_id=0, $where='',$orderby = '',$user_name='',$user_pwd='',$is_all=false)
{

    $time = TIME_UTC;

    $count_sql = "select count(*) from ".DB_PREFIX."deal where 1=1 ";
    if($is_all==false)
        $count_sql.=" and is_effect = 1 and is_delete = 0 ";

    if(\es_cookie::get("shop_sort_field")=="ulevel"){
        $extfield = ",(SELECT u.level_id FROM fanwe_user u WHERE u.id=user_id ) as ulevel";
    }

    $sql = "select *,start_time as last_time,(load_money/borrow_amount*100) as progress_point,(start_time + enddate*24*3600 - ".$time.") as remain_time $extfield from ".DB_PREFIX."deal where 1 = 1 ";
    if($is_all==false)
        $sql.=" and is_effect = 1 and is_delete = 0 ";

    if($cate_id>0)
    {
        $ids =load_auto_cache("deal_sub_parent_cate_ids",array("cate_id"=>$cate_id));
        $sql .= " and cate_id in (".implode(",",$ids).")";
        $count_sql .= " and cate_id in (".implode(",",$ids).")";
    }

    if($where != '')
    {
        $sql.=" and ".$where;
        $count_sql.=" and ".$where;
    }

    if($orderby=='')
        $sql.=" order by sort desc ";
    else
        $sql.=" order by ".$orderby;

    if($limit!=""){
        $sql .=" limit ".$limit;
    }
    $deals_count = $GLOBALS['db']->getOne($count_sql);
    if($deals_count > 0){
        $deals = $GLOBALS['db']->getAll($sql);
        if($deals)
        {
            foreach($deals as $k=>$deal)
            {
                format_deal_item($deal,$user_name,$user_pwd);
                $deals[$k] = $deal;
            }
        }
    }
    else{
        $deals = array();
    }
    return array('list'=>$deals,'count'=>$deals_count);
}

function format_deal_item(&$deal,$user_name="",$user_pwd=""){

    //判断是否已经开始
    $deal['is_wait'] = 0;
    if($deal['start_time'] > TIME_UTC){
        $deal['is_wait'] = 1;
        $deal['remain_time'] = $deal['start_time'] - TIME_UTC;
    }
    else{
        $deal['remain_time'] = $deal['start_time'] + $deal['enddate']*24*3600 - TIME_UTC;
    }

    $deal['loantype_format'] = loantypename($deal['loantype'],1);

    //当为天的时候
    if($deal['repay_time_type'] == 0){
        $true_repay_time = 1;
    }
    else{
        $true_repay_time = $deal['repay_time'];
    }

    if(trim($deal['titlecolor']) != ''){
        $deal['color_name'] = "<span style='color:#".$deal['titlecolor']."'>".$deal['name']."</span>";
    }
    else{
        $deal['color_name'] = $deal['name'];
    }
    //格式化数据
    if($deal['apart_borrow_amount'])
        $deal['borrow_amount_format'] = format_price($deal['apart_borrow_amount']/10000)."万";
    else
        $deal['borrow_amount_format'] = format_price($deal['borrow_amount']/10000)."万";

    $deal['load_money'] = getCollWaitMoney($deal) + $deal['load_money'];

    $deal['load_money_format'] = format_price($deal['load_money']/10000)."万";

    $deal['rate_foramt'] = number_format($deal['rate'],2);

    $deal['create_time_format'] = to_date($deal['create_time'],'Y-m-d');

    //$deal['borrow_amount_format_w'] = format_price($deal['borrow_amount']/10000)."万";
    $deal['rate_foramt_w'] = number_format($deal['rate'],2)."%";

    $deal_repay_rs = deal_repay_money($deal);

    //本息还款金额
    $deal['month_repay_money'] = $deal_repay_rs['month_repay_money'];

    //最后一期还款
    $deal['last_month_repay_money'] = $deal_repay_rs['last_month_repay_money'];

    $deal['month_repay_money_format'] = format_price($deal['month_repay_money']);

    //到期还本息管理费
    if($deal['repay_time_type']==1) //月标
    {
        $deal['month_manage_money'] = $deal['borrow_amount']*(float)$deal['manage_fee']/100;
        //总的多少管理费
        $deal['all_manage_money'] = $deal['month_manage_money'] * $deal["repay_time"];
    }else{ //天标
        $deal['month_manage_money'] = $deal['borrow_amount']*(float)$deal['manage_fee']*$deal["repay_time"]/100/30;
        //总的多少管理费
        $deal['all_manage_money'] = $deal['month_manage_money'];
    }


    $deal['month_manage_money_format'] = format_price($deal['month_manage_money']);


    if(is_last_repay($deal['loantype'])==1){
        $deal['true_month_repay_money'] = $deal['month_repay_money'] + $deal['all_manage_money'];
        $deal['true_last_month_repay_money'] = $deal['last_month_repay_money'] + $deal['all_manage_money'];
    }
    elseif(is_last_repay($deal['loantype'])==2){
        $deal['month_manage_money'] = $deal['month_manage_money'] *3;
        $deal['true_month_repay_money'] = $deal['month_repay_money'] + $deal['month_manage_money'];
        $deal['true_last_month_repay_money'] = $deal['last_month_repay_money'] + $deal['month_manage_money'];
    }
    else{
        $deal['true_month_repay_money'] = $deal['month_repay_money'] + $deal['month_manage_money'];
        $deal['true_last_month_repay_money'] = $deal['last_month_repay_money'] + $deal['month_manage_money'];
    }

    $deal['true_month_repay_money_format'] = format_price($deal['true_month_repay_money']);

    //还需多少钱
    $deal['need_money'] = format_price($deal['borrow_amount'] - $deal['load_money']);//计算锁定了的钱
    //百分比
    $deal['progress_point'] = $deal['load_money']/$deal['borrow_amount']*100;

    $deal['user'] = get_user("*",$deal['user_id']);

    if($deal['cate_id'] > 0){
        $deal['cate_info'] = $GLOBALS['db']->getRow("select id,name,brief,uname,icon from ".DB_PREFIX."deal_cate where id = ".$deal['cate_id']." and is_effect = 1 and is_delete = 0",false);
    }
    if($deal['type_id'] > 0){
        $deal['type_info'] = get_loantype_info($deal['type_id']);
        if($deal['deal_status'] == 0){
            $deal['need_credit'] = 0; //0不需要材料，1需要材料
            $credits = unserialize($deal['type_info']['credits']);
            $user_credit = get_user_credit_file($deal['user_id']);
            foreach($credits as $kk=>$vv){
                if($user_credit[$vv]['passed']==0){
                    $deal['need_credit'] += 1;
                }
            }

        }
    }

    if($deal['agency_id'] > 0){
        $deal['agency_info'] = get_user("*",$deal['agency_id']);
        if($deal['agency_info']['view_info']!=""){
            $deal['agency_info']['view_info_list'] = unserialize($deal['agency_info']['view_info']);
        }
    }

    //前台显示图片
    if($deal['mortgage_infos']!=""){
        $deal['deal_mortgage_infos_list'] = unserialize($deal['mortgage_infos']);
    }

    if($deal['is_mortgage'] == 1){
        if($deal['mortgage_infos']!=""){
            $deal['mortgage_infos_list'] = unserialize($deal['mortgage_infos']);
        }

        if($deal['repay_time_type']==1)
            $deal['all_mortgage_fee'] = $deal['mortgage_fee'] * $deal["repay_time"];
        else
            $deal['all_mortgage_fee'] = $deal['mortgage_fee'] ;
    }
    else{
        $deal['mortgage_fee'] = 0;
        $deal['all_mortgage_fee'] = 0;
    }

    if($deal['mortgage_contract']!=""){
        $deal['mortgage_contract_list'] = unserialize($deal['mortgage_contract']);
    }

    if($deal['deal_status'] <> 1 || $deal['remain_time'] <= 0){
        $deal['remain_time_format'] = "0".$GLOBALS['lang']['DAY']."0".$GLOBALS['lang']['HOUR']."0".$GLOBALS['lang']['MIN'];
    }
    else{
        $deal['remain_time_format'] = remain_time($deal['remain_time']);
    }

    $deal['min_loan_money_format'] = format_price($deal['min_loan_money']);

    if($deal['uloadtype'] == 1){
        if($deal['buy_count'] == 0)
            $deal['buy_portion'] = 0;
        else
            $deal['buy_portion'] = intval($deal['load_money']/$deal['min_loan_money']);

        $deal['need_portion'] = intval(($deal['borrow_amount'] - $deal['load_money'] ) / $deal['min_loan_money']);
    }

    if($deal['deal_status']>=4){

        //总的必须还多少本息
        $deal['remain_repay_money'] = $deal_repay_rs['remain_repay_money'];

        //还有多少需要还
        $deal['need_remain_repay_money'] = floatval($deal['remain_repay_money']) - floatval($deal['repay_money']);

        //还款进度条
        if($deal['remain_repay_money'] > 0)
        {
            $deal['repay_progress_point'] =  $deal['repay_money']/$deal['remain_repay_money']*100;
            if($deal['deal_status'] == 5){
                $deal['progress_point'] = 100;
            }else{
                $deal['progress_point'] = $deal['repay_progress_point'];
            }
        }else
        {
            $deal['repay_progress_point'] =  0;
        }




        //最后的还款日期
        if($deal['repay_time_type'] == 0)
            $deal["end_repay_time"] =  $deal['repay_start_time'] + $deal['repay_time']*24*3600;
        else
            $deal["end_repay_time"] =  next_replay_month($deal['repay_start_time'],$true_repay_time);

        if($deal['deal_status']==4){

            $has_repay_money = $GLOBALS['db']->getOne("SELECT sum(true_repay_money + impose_money + true_repay_manage_money + repay_manage_impose_money) FROM ".DB_PREFIX."deal_load_repay WHERE deal_id=".$deal['id']." AND repay_time=".$deal['next_repay_time']);

            $deal['true_month_repay_money'] = $deal['true_month_repay_money'] - floatval($has_repay_money);
            $deal['true_last_month_repay_money'] = $deal['true_last_month_repay_money'] - floatval($has_repay_money);

            $deal["next_repay_time_format"] = to_date($deal['next_repay_time'],'Y-m-d');

            if(to_date($deal["end_repay_time"],"Ymd") < to_date(TIME_UTC,"Ymd")){
                $deal['exceed_the_time'] = true;
            }

            //罚息
            $is_check_impose = true;
            //到期还本息 只有最后一个月后才算罚息
            if($deal_repay_rs['is_check_impose'] == true){
                //算出到期还本息的最后一个月是否小于今天
                if($deal['exceed_the_time']){
                    $is_check_impose = true;
                }
                else{
                    $is_check_impose = false;
                }
            }
            if($deal["next_repay_time"] - TIME_UTC < 0 && $is_check_impose){
                //晚多少天
                $time_span = to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d");
                $next_time_span = to_timespan(to_date($deal['next_repay_time'],"Y-m-d"),"Y-m-d");
                $day  = ceil(($time_span-$next_time_span)/24/3600);

                $impose_fee = trim($deal['impose_fee_day1']);
                $manage_impose_fee = trim($deal['manage_impose_fee_day1']);
                //判断是否严重逾期
                if($day >= app_conf('YZ_IMPSE_DAY')){
                    $impose_fee = trim($deal['impose_fee_day2']);
                    $manage_impose_fee = trim($deal['manage_impose_fee_day2']);
                }

                $impose_fee = floatval($impose_fee);
                $manage_impose_fee = floatval($manage_impose_fee);

                //罚息
                if((int)$deal['next_repay_time'] == (int)$deal['end_repay_time']){
                    $deal['impose_money'] = $deal['last_month_repay_money']*$impose_fee*$day/100;
                    $deal['manage_impose_money'] = $deal['last_month_repay_money']*$manage_impose_fee*$day/100;
                }
                else{
                    $deal['impose_money'] = $deal['month_repay_money']*$impose_fee*$day/100;
                    //罚管理费
                    $deal['manage_impose_money'] = $deal['month_repay_money']*$manage_impose_fee*$day/100;
                }
                $deal['impose_money'] += $deal['manage_impose_money'];
            }
        }
    }

    if($deal['publish_wait'] == 1 || $deal['publish_wait'] == 0){
        $deal['publish_time_format'] = to_date($deal['create_time'],'Y-m-d H:i');
    }else{
        $deal['publish_time_format'] = to_date($deal['start_time'],'Y-m-d H:i');
    }

    if($GLOBALS['request']['from'] == "wap")
    {
        $durl = url_wap("index","deal",array("id"=>$deal['id']));
    }
    else
    {
        $durl = url("index","deal",array("id"=>$deal['id']));
    }
    $deal['share_url'] = SITE_DOMAIN.APP_ROOT.$durl;
    if($GLOBALS['user_info'])
    {
        if(app_conf("URL_MODEL")==0)
        {
            $deal['share_url'] .= "&r=".base64_encode(intval($GLOBALS['user_info']['id']));
        }
        else
        {
            $deal['share_url'] .= "?r=".base64_encode(intval($GLOBALS['user_info']['id']));
        }
    }

    $deal['url'] = $durl;
    if (!empty($user_name) && !empty($user_pwd)){
        $durl = "/index.php?ctl=uc_deal&act=mrefdetail&is_sj=1&id=".$deal['id']."&user_name=".$user_name."&user_pwd=".$user_pwd;
    }else{
        $durl =wap_url("index","deal_mobile",array("id"=>$deal['id']));
    }

    $deal['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.APP_ROOT.$durl);
}

/**
 * 还款列表
 */
function get_deal_load_list($deal){

    //当为天的时候
    if($deal['repay_time_type'] == 0){
        $true_repay_time = 1;
    }
    else{
        $true_repay_time = $deal['repay_time'];
    }


    $deal_repay_list = $GLOBALS['db']->getAll("SELECT *,l_key+1 as l_key_index FROM ".DB_PREFIX."deal_repay where deal_id=".$deal['id']." order by l_key ASC ");

    $tmp_has_repay_money = $GLOBALS['db']->getAll("SELECT repay_id,sum(true_repay_money + impose_money + true_repay_manage_money + repay_manage_impose_money) as has_repay_money FROM ".DB_PREFIX."deal_load_repay WHERE deal_id=".$deal['id']." GROUP BY repay_id");
    $has_repay_money = array();
    foreach($tmp_has_repay_money as $kk=>$vv){
        $has_repay_money[$vv['repay_id']] = $vv['has_repay_money'];
    }
    unset($tmp_has_repay_money);

    foreach($deal_repay_list as $k=>$v){

        $i = $v['l_key'];
        $loan_list[$i]['get_manage'] = $v['get_manage'];
        $loan_list[$i]['l_key'] = $v['l_key'];
        $loan_list[$i]['l_key_index'] = $v['l_key_index'];
        $loan_list[$i]['repay_id'] = $v['id'];
        $loan_list[$i]['impose_day'] = 0;
        /**
         * status 1提前,2准时还款，3逾期还款 4严重逾期 5部分还款 6还款中
         */
        if($v['has_repay'] == 2){
            $loan_list[$i]['status'] = 5;
        }
        elseif($v['has_repay'] == 3){
            $loan_list[$i]['status'] = 6;
        }

        $loan_list[$i]['repay_day'] = $v['repay_time'];

        //月还本息
        $loan_list[$i]['month_repay_money'] = $v['repay_money'];
        //判断是否已经还完
        $loan_list[$i]['true_repay_time'] = $v['true_repay_time'];
        //管理费
        $loan_list[$i]['month_manage_money'] = $v['manage_money'] - $v['true_manage_money'];
        //抵押物管理费
        $loan_list[$i]['mortgage_fee'] = $v['mortgage_fee'] - $v['true_mortgage_fee'];

        //返佣
        $loan_list[$i]['manage_money_rebate'] = (float)$v['manage_money_rebate'];

        //has_repay：1：已还款;0:未还款
        $loan_list[$i]['has_repay'] = $v['has_repay'];

        //已还多少
        $loan_list[$i]['month_has_repay_money'] = 0;

        //总罚息 =  罚息管理费 + 逾期管理费
        $loan_list[$i]['impose_all_money'] = 0;
        if($v['has_repay'] == 1){
            $loan_list[$i]['month_has_repay_money'] = $v['true_repay_money'];
            $loan_list[$i]['month_manage_money'] = $v['true_manage_money'];
            //返佣
            $loan_list[$i]['manage_money_rebate'] = (float)$v['true_manage_money_rebate'];

            $loan_list[$i]['status'] = $v['status']+1;

            $loan_list[$i]['month_repay_money'] =0;

            $loan_list[$i]['mortgage_fee'] = $v['true_mortgage_fee'];

            //逾期罚息
            $loan_list[$i]['impose_money'] = $v['impose_money'];

            //逾期管理费
            $loan_list[$i]['manage_impose_money'] = $v['manage_impose_money'];

            //真实还多少
            $loan_list[$i]['month_has_repay_money_all'] = $loan_list[$i]['month_has_repay_money'] + $loan_list[$i]['month_manage_money']+$loan_list[$i]['impose_money']+$loan_list[$i]['manage_impose_money'] + $loan_list[$i]['mortgage_fee'];

            //总的必须还多少
            $loan_list[$i]['month_need_all_repay_money'] = 0;

            $loan_list[$i]['impose_all_money'] = $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'];

        }
        elseif($v['has_repay'] == 0){
            //判断是否罚息
            if(TIME_UTC > ($v['repay_time']+ 24*3600 -1)&& $loan_list[$i]['month_repay_money'] > 0){
                //晚多少天
                $loan_list[$i]['status'] = 3;
                $time_span = to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d");
                $next_time_span = $v['repay_time'];
                $day  = ceil(($time_span-$next_time_span)/24/3600);

                $loan_list[$i]['impose_day'] = $day;

                $impose_fee = trim($deal['impose_fee_day1']);
                $manage_impose_fee = trim($deal['manage_impose_fee_day1']);
                //严重逾期费率
                if($day >= app_conf('YZ_IMPSE_DAY')){
                    $loan_list[$i]['status'] = 4;
                    $impose_fee = trim($deal['impose_fee_day2']);
                    $manage_impose_fee = trim($deal['manage_impose_fee_day2']);
                }

                $impose_fee = floatval($impose_fee);
                $manage_impose_fee = floatval($manage_impose_fee);

                //罚息
                $loan_list[$i]['impose_money'] = $loan_list[$i]['month_repay_money']*$impose_fee*$day/100;

                //罚管理费
                $loan_list[$i]['manage_impose_money'] = $loan_list[$i]['month_repay_money']*$manage_impose_fee*$day/100;
                $loan_list[$i]['impose_all_money'] = $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'];
            }
            /*elseif(to_date(TIME_UTC,"Y-m-d") == to_date($v['repay_time'],"Y-m-d") || (((int)$v['repay_time'] - TIME_UTC)/24/3600 <=3 && ((int)$v['repay_time'] - TIME_UTC)/24/3600 >=0)){
                $loan_list[$i]['status'] =  2;
            }
            else{
                $loan_list[$i]['status'] =  1;
            }*/
            else{
                //判断是否罚息
                if(TIME_UTC > ($v['repay_time']+ 24*3600 -1)&& $loan_list[$i]['month_repay_money'] > 0){
                    //晚多少天
                    $loan_list[$i]['status'] = 3;
                    $time_span = to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d");
                    $next_time_span = $v['repay_time'];
                    $day  = ceil(($time_span-$next_time_span)/24/3600);

                    $loan_list[$i]['impose_day'] = $day;

                    $impose_fee = trim($deal['impose_fee_day1']);
                    $manage_impose_fee = trim($deal['manage_impose_fee_day1']);
                    //严重逾期费率
                    if($day >= app_conf('YZ_IMPSE_DAY')){
                        $loan_list[$i]['status'] = 4;
                        $impose_fee = trim($deal['impose_fee_day2']);
                        $manage_impose_fee = trim($deal['manage_impose_fee_day2']);
                    }

                    $impose_fee = floatval($impose_fee);
                    $manage_impose_fee = floatval($manage_impose_fee);

                    //罚息
                    $loan_list[$i]['impose_money'] = $loan_list[$i]['month_repay_money']*$impose_fee*$day/100;

                    //罚管理费
                    $loan_list[$i]['manage_impose_money'] = $loan_list[$i]['month_repay_money']*$manage_impose_fee*$day/100;
                    $loan_list[$i]['impose_all_money'] = $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'];
                }
                $loan_list[$i]['status'] =  2;
            }

            //真实还多少
            $loan_list[$i]['month_has_repay_money_all'] = $has_repay_money[$v['id']];

            //总的必须还多少
            $loan_list[$i]['month_need_all_repay_money'] =  $loan_list[$i]['month_repay_money'] + $loan_list[$i]['month_manage_money'] + $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'] + $loan_list[$i]['mortgage_fee'];
        }
        elseif($v['has_repay'] == 2){
            //判断是否罚息
            $ss_repay_info = $GLOBALS['db']->getRow("SELECT sum(repay_money) as month_repay_money,sum(repay_manage_money) as month_manage_money FROM ".DB_PREFIX."deal_load_repay WHERE l_key =".$i." and deal_id=".$deal['id']." and has_repay=0 ");

            $tmp_month_repay_money = $loan_list[$i]['month_repay_money'];
            $loan_list[$i]['month_repay_money'] = $ss_repay_info['month_repay_money'];
            $loan_list[$i]['month_manage_money']= $ss_repay_info['month_manage_money'];
            if(TIME_UTC > ($v['repay_time']+ 24*3600 -1)&& $loan_list[$i]['month_repay_money'] > 0){
                $loan_list[$i]['status'] = 3;
                //晚多少天
                $time_span = to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d");
                $next_time_span = $v['repay_time'];
                $day  = ceil(($time_span-$next_time_span)/24/3600);

                $loan_list[$i]['impose_day'] = $day;

                $impose_fee = trim($deal['impose_fee_day1']);
                $manage_impose_fee = trim($deal['manage_impose_fee_day1']);
                //严重逾期费率
                if($day >= app_conf('YZ_IMPSE_DAY')){
                    $loan_list[$i]['status'] = 4;
                    $impose_fee = trim($deal['impose_fee_day2']);
                    $manage_impose_fee = trim($deal['manage_impose_fee_day2']);
                }

                $impose_fee = floatval($impose_fee);
                $manage_impose_fee = floatval($manage_impose_fee);

                //罚息
                $loan_list[$i]['impose_money'] = $loan_list[$i]['month_repay_money']*$impose_fee*$day/100;


                //罚管理费
                $loan_list[$i]['manage_impose_money'] = $loan_list[$i]['month_repay_money']*$manage_impose_fee*$day/100;
                $loan_list[$i]['impose_all_money'] = $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'];
            }
            /*elseif(to_date(TIME_UTC,"Y-m-d") == to_date($v['repay_time'],"Y-m-d") || (((int)$v['repay_time'] - TIME_UTC)/24/3600 <=3 && ((int)$v['repay_time'] - TIME_UTC)/24/3600 >=0)){

                $loan_list[$i]['status'] =  2;
            }
            elseif(round($tmp_month_repay_money) <= $loan_list[$i]['month_repay_money']){
                $loan_list[$i]['has_repay'] =  0;
            }
            else{
                $loan_list[$i]['status'] =  1;
            }*/
            else{
                $loan_list[$i]['status'] =  2;
            }
            $loan_list[$i]['has_repay'] =  0;

            //真实还多少
            $loan_list[$i]['month_has_repay_money_all'] = $has_repay_money[$v['id']];

            //总的必须还多少
            $loan_list[$i]['month_need_all_repay_money'] =  $loan_list[$i]['month_repay_money'] + $loan_list[$i]['month_manage_money'] + $loan_list[$i]['impose_money'] + $loan_list[$i]['manage_impose_money'] + $loan_list[$i]['mortgage_fee'];
        }

        //还款日
        $loan_list[$i]['repay_day_format'] = to_date($loan_list[$i]['repay_day'],'Y-m-d');
        //已还金额
        $loan_list[$i]['month_has_repay_money_all_format'] = format_price($loan_list[$i]['month_has_repay_money_all']);
        //待还金额
        $loan_list[$i]['month_need_all_repay_money_format'] = format_price($loan_list[$i]['month_need_all_repay_money']);

        //待还本息
        $loan_list[$i]['month_repay_money_format'] = format_price($loan_list[$i]['month_repay_money']);
        //借款管理费
        $loan_list[$i]['month_manage_money_format'] = format_price($loan_list[$i]['month_manage_money']);
        //抵押物管理费
        $loan_list[$i]['mortgage_fee_format'] = format_price($loan_list[$i]['mortgage_fee']);
        //返佣
        $loan_list[$i]['manage_money_rebate_format'] = format_price($loan_list[$i]['manage_money_rebate']);

        //借款管理费
        $loan_list[$i]['manage_money_impose_format'] = format_price($loan_list[$i]['manage_impose_money']);

        //逾期费用
        $loan_list[$i]['impose_money_format'] = format_price($loan_list[$i]['impose_money']);

        //逾期、违约金
        $loan_list[$i]['impose_all_money_format'] = format_price($loan_list[$i]['impose_all_money']);

        //状态
        if($loan_list[$i]['has_repay'] == 0){
            $loan_list[$i]['status_format'] = '待还';
        }
        elseif($loan_list[$i]['status'] == 1){
            $loan_list[$i]['status_format'] = '提前还款';
        }elseif($loan_list[$i]['status'] == 2){
            $loan_list[$i]['status_format'] = '正常还款';
        }elseif($loan_list[$i]['status'] == 3){
            $loan_list[$i]['status_format'] = '逾期还款';
        }elseif($loan_list[$i]['status'] == 4){
            $loan_list[$i]['status_format'] = '严重逾期';
        }elseif($loan_list[$i]['status'] == 5){
            $loan_list[$i]['status_format'] = '部分还款';
        }
        elseif($loan_list[$i]['status'] == 6){
            $loan_list[$i]['status_format'] = '还款中';
        }


    }


    return $loan_list;
}


/**
 * 获取某一期的用户还款列表
 * array $deal_info 借款信息
 * int $user_id 用户ID 为0代表全部
 * int $lkey  第几期 -1 全部
 * int $ukey 第几个投标人 -1 全部
 * int $true_time  真实还款时间
 * int $get_type  0 全部 1代表未还的  2 代表已还的
 * int $r_type = 0; 返回类型; 1:只返回一个数组; $result['item']
 * string $limit; 查询限制数量; 0,20  $result['count']
 *
 *
 * 还款 时（has_repay = 0)
 *
 * “平台”收取的费用
 * 	：借款者 的管理费 + 管理逾期罚息  $v['repay_manage_money'] + $v['repay_manage_impose_money'];
 * 	：投资者 的(本金)管理费 + 利息管理费  $v['manage_money'] + $v['manage_interest_money'];
 *
 * “投资者” 收取的费用
 * 	：本金 + 利息 + 罚息 - (本金)管理费 - 利息管理费
 * 		$v['self_money'] + $v['interest_money'] + $v['impose_money'] - $v['manage_money'] - $v['manage_interest_money']
 * 	：奖励 （奖励费用，由平台支出）
 * 		$v['reward_money']
 * 	注：$item['month_repay_money'] = $v['repay_money'] = $v['self_money'] + $v['interest_money']
 *
 *
 * “借款者” 需要支出的费用 = 借款者 的管理费 + 管理逾期罚息 + (本金 + 利息 + 罚息)
 * 	 $v['repay_manage_money'] + $v['repay_manage_impose_money'] + $v['self_money'] + $v['interest_money'] + $v['impose_money']
 *
 *
 * “平台” 需要支付
 * 	支付给“投资者”的奖励 $v['reward_money']
 * 	支付给“推荐人”的  [“投资者”利息管理费返利 ] $v['manage_interest_money_rebate']
 *
 *  支付给“推荐人”的 [“借款者”管理费返利 ] fanwe.fanwe_deal_repay.manage_money_rebate 需要本期所有的还完后，才计算
 */

function get_deal_user_load_list($deal_info, $user_id = 0 ,$lkey = -1 , $ukey = -1,$true_time=0,$get_type = 0, $r_type = 0, $limit = ""){
    if(!$deal_info){
        return false;
    }

    $result = array();

    if($get_type > 0){
        if($get_type==1)
            $extW = " AND dlr.has_repay = 0 ";
        else
            $extW = " AND dlr.has_repay = 1 ";
    }

    if($user_id > 0){
        $extW .= " AND ((dlr.user_id =  ".$user_id." and dlr.t_user_id = 0 ) or dlr.t_user_id = ".$user_id.")";
    }

    if($lkey >= 0){
        $extW .= " AND dlr.l_key =  ".$lkey;
    }

    if (!empty($limit)){
        $limit = " limit ".$limit;

        $sql = "SELECT count(*) FROM ".DB_PREFIX."deal_load_repay dlr ".
            " WHERE dlr.deal_id=".$deal_info['id']." $extW";

        $count = $GLOBALS['db']->getOne($sql);
        $result['count'] = $count;
    }


    $sql = "SELECT dlr.*,dl.interestrate_id,dl.pMerBillNo,dl.money,dl.is_winning,dl.income_type,income_value,u.ips_acct_no,AES_DECRYPT(u.mobile_encrypt,'".AES_DECRYPT_KEY."') AS mobile,AES_DECRYPT(u.email_encrypt,'".AES_DECRYPT_KEY."') AS email,u.user_name,tu.ips_acct_no as t_ips_acct_no,tu.id as t_user_id,tu.user_name as t_user_name,AES_DECRYPT(tu.mobile_encrypt ,'".AES_DECRYPT_KEY."') AS t_mobile,AES_DECRYPT(tu.email_encrypt ,'".AES_DECRYPT_KEY."') AS t_email,dl.learn_id,dl.learn_money,dl.back_learn_money  FROM ".DB_PREFIX."deal_load_repay dlr ".

        " LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id =dlr.load_id  ".
        " LEFT OUTER JOIN ".DB_PREFIX."user u ON u.id = dlr.user_id ".
        " LEFT OUTER JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.load_id = dl.id and dlt.near_repay_time <=dlr.repay_time ".
        " LEFT OUTER JOIN ".DB_PREFIX."user tu ON tu.id = dlt.t_user_id ".
        " WHERE dlr.deal_id=".$deal_info['id']." $extW ORDER BY dlr.l_key ASC,dlr.u_key ASC ".$limit;

    $load_users = $GLOBALS['db']->getAll($sql);

    if($true_time == 0)
        $true_time = TIME_UTC;



    $loan_list = array();
    foreach($load_users as $k=>$v){

        $item = array();

        //deal_load_repay 编号
        $item['id'] = $v['id'];

        $item['learn_id'] = $v['learn_id'];
        $item['load_id'] = $v['load_id'];
        $item['learn_money'] = $v['learn_money'];
        $item['back_learn_money'] = $v['back_learn_money'];

        //status 1提前,2准时还款，3逾期还款 4严重逾期 数据库里的参数 + 1
        if($v['has_repay'] == 1){
            $item['status'] = $v['status'] +1;
        }

        //实际投标金额
        $item['money'] = $v['money'];

        //还款日
        $item['repay_day'] = $v['repay_time'];

        //实际还款日
        $item['true_repay_time'] = $v['true_repay_time'];

        //月还本息
        $item['month_repay_money']= $v['true_repay_money'];

        //当前期本金
        $item['self_money'] = $v['true_self_money'];

        //罚息
        $item['impose_money'] =$v['impose_money'];


        $item['interest_money'] = $v['true_interest_money'];

        //加息券
        $item['interestrate_money'] = $v['interestrate_money'];
        $item['interestrate_id'] = $v['interestrate_id'];

        //投标者信息
        $item['user_id'] =$v['user_id'];
        $item['user_name'] =$v['user_name'];
        $item['email'] =$v['email'];
        $item['mobile'] =$v['mobile'];
        $item['ips_acct_no'] =$v['ips_acct_no'];

        //承接者信息
        $item['t_user_id'] =$v['t_user_id'];
        $item['t_user_name'] =$v['t_user_name'];
        $item['t_ips_acct_no'] =$v['t_ips_acct_no'];
        $item['t_email'] =$v['t_email'];
        $item['t_mobile'] =$v['t_mobile'];

        //管理费
        $item['manage_money'] =$v['true_manage_money'];

        //利息管理费
        $item['manage_interest_money'] =$v['true_manage_interest_money'];

        //借款者均摊下来的管理费
        $item['repay_manage_money'] =$v['repay_manage_money'];
        //借款者均摊下来的抵押物管理费
        $item['mortgage_fee'] =$v['mortgage_fee'];

        //是否还款 0未还 1已还
        $item['has_repay'] =$v['has_repay'];

        //对应deal_repay的编号
        $item['repay_id'] =$v['repay_id'];
        //投标编号 对应 deal_load 的编号
        $item['load_id'] =$v['load_id'];
        //第几期
        $item['l_key'] =$v['l_key'];
        $item['l_key_index'] =$v['l_key']+1;


        //对应借款的第几个投标人
        $item['u_key'] =$v['u_key'];
        //登记债权人时提 交的订单号
        $item['pMerBillNo'] =$v['pMerBillNo'];
        //逾期借入者管理费罚息
        $item['repay_manage_impose_money'] = $v['repay_manage_impose_money'];
        //返佣
        $item['manage_interest_money_rebate'] = $v['true_manage_interest_money_rebate'];

        $item['true_manage_interest_money_rebate'] = $v['true_manage_interest_money_rebate'];

        $item['t_pMerBillNo'] = $v['t_pMerBillNo'];

        if($v['has_repay'] == 0){
            //月还本息
            $item['month_repay_money']= $v['repay_money'];
            //管理费
            $item['manage_money'] =$v['manage_money'];
            //利息管理费
            $item['manage_interest_money'] =$v['manage_interest_money'];
            $item['repay_manage_money'] = $v['repay_manage_money'];
            $item['self_money'] = $v['self_money'];
            $item['interest_money'] = $v['interest_money'];
            $item['repay_manage_impose_money'] = $v['repay_manage_impose_money'];
            //返佣
            $item['manage_interest_money_rebate'] = $v['manage_interest_money_rebate'];

            $item['month_has_repay_money'] = 0;
            if($true_time > ($v['repay_time'] + 24*3600 -1 ) && $item['month_repay_money'] > 0){
                $time_span = to_timespan(to_date($true_time,"Y-m-d"),"Y-m-d");
                $next_time_span = $v['repay_time'];
                $item['impose_day'] = $day  = ceil(($time_span-$next_time_span)/24/3600);


                if($day >0){
                    //普通逾期
                    $item['status'] = 3;
                    $impose_fee = trim($deal_info['impose_fee_day1']);
                    $manage_impose_fee = trim($deal_info['manage_impose_fee_day1']);
                    if($day >= app_conf('YZ_IMPSE_DAY')){//严重逾期
                        $impose_fee = trim($deal_info['impose_fee_day2']);
                        $manage_impose_fee = trim($deal_info['manage_impose_fee_day2']);
                        $item['status'] = 4;
                    }

                    $impose_fee = floatval($impose_fee);

                    //罚息
                    $item['impose_money'] = $item['month_repay_money'] *$impose_fee*$day/100;

                    $item['repay_manage_impose_money'] = $item['month_repay_money']*$manage_impose_fee*$day/100;
                }

            }
            /*elseif(to_date($true_time,"Y-m-d") == to_date($v['repay_time'],"Y-m-d")  || (((int)$v['repay_time'] - $true_time)/24/3600 <=3 && ((int)$v['repay_time'] - $true_time)/24/3600 >=0)){
                $item['status'] = 2;
            }
            else{
                $item['status'] = 1;
            }*/
            else{
                $item['status'] = 2;
            }
            $item['month_has_repay_money'] = 0;
            $item['month_has_repay_money_all'] = 0;
        }
        elseif($v['has_repay'] == 2){
            //月还本息
            $item['month_repay_money']= $v['repay_money'];
            //管理费
            $item['manage_money'] =$v['manage_money'];
            //利息管理费
            $item['manage_interest_money'] =$v['manage_interest_money'];
            $item['repay_manage_money'] =$v['repay_manage_money'];
            $item['self_money'] = $v['self_money'];
            $item['interest_money'] = $v['interest_money'];
            $item['repay_manage_impose_money'] = $v['repay_manage_impose_money'];
            //返佣
            $item['manage_interest_money_rebate'] = $v['manage_interest_money_rebate'];
            $item['month_has_repay_money'] = 0;
            $item['month_has_repay_money_all'] = 0;
        }
        else{
            $item['month_has_repay_money'] = $item['month_repay_money'];
            $item['month_has_repay_money_all'] = $item['month_repay_money'] + $item['month_manage_money']+$item['impose_money'];
        }

        $item['expect_earnings'] = $v['interest_money'] - $v['manage_money'] - $v['manage_interest_money'] + $v['reward_money'];
        if($item['has_repay']==1){
            $item['true_earnings'] = $v['true_interest_money'] + $item['impose_money'] - $v['true_manage_money'] - $v['true_manage_interest_money'] + $v['true_reward_money'];
        }
        else{
            $item['expect_earnings'] += $item['impose_money'];
            $item['true_earnings'] = 0;
        }

        $item['repay_day_format'] = to_date($item['repay_day'],"Y-m-d");
        $item['true_repay_time_format'] = to_date($item['true_repay_time']);
        $item['true_repay_day_format'] = to_date($item['true_repay_time'],"Y-m-d");
        $item['manage_money_format'] = format_price($item['manage_money']);
        $item['manage_interest_money_format'] = format_price($item['manage_interest_money']);
        $item['impose_money_format'] = format_price($item['impose_money']);
        $item['repay_manage_impose_money_format'] = format_price($item['repay_manage_impose_money']);
        $item['manage_interest_money_rebate_format'] = format_price($item['manage_interest_money_rebate']);
        $item['month_repay_money_format'] = format_price($item['month_repay_money']);
        $item['month_has_repay_money_format'] = format_price($item['month_has_repay_money']);
        $item['month_has_repay_money_all_format'] = format_price($item['month_has_repay_money_all']);
        //状态
        if($item['has_repay'] == 0){
            $item['status_format'] = '待还';
        }elseif($item['status'] == 1){
            $item['status_format'] = '提前还款';
        }elseif($item['status'] == 2){
            $item['status_format'] = '正常还款';
        }elseif($item['status'] == 3){
            $item['status_format'] = '逾期还款';
        }elseif($item['status'] == 4){
            $item['status_format'] = '严重逾期';
        }

        $item['site_repay_format'] = "";
        if($v['has_repay']==1){
            if($v['is_site_repay'] == 0){
                $item['site_repay_format'] = "会员";
            }
            elseif($v['is_site_repay'] == 1){
                $item['site_repay_format'] = "网站";
            }
            elseif($v['is_site_repay'] == 2){
                $item['site_repay_format'] = "机构";
            }
        }


        if ($r_type == 0){
            if($lkey >= 0){
                if($lkey == $item['l_key']){
                    $loan_list[$item['u_key']][$item['l_key']] = $item;
                }
            }
            else
                $loan_list[$item['u_key']][$item['l_key']] = $item;
        }else{
            $loan_list[] = $item;
        }
    }

    if ($r_type == 0){
        if($ukey >= 0)
            return $loan_list[$ukey];
        else{
            return $loan_list;
        }
    }else{
        $result['item'] = $loan_list;
        return $result;
    }
}


function check_dobid2($deal_id,$bid_money,$bid_paypassword,$is_pc = 0,$ecv_id=0,$learn_id = 0,$interestrate_id=0,$use_interestrate=0){

    $root = array();
    $root["status"] = 0;//0:出错;1:正确;

    $bid_money = floatval($bid_money);
    $bid_paypassword = strim($bid_paypassword);
    $GLOBALS['user_info'] = \es_session::get('user_info');

    if(!$GLOBALS['user_info']){
        $root["show_err"] = l('PLEASE_LOGIN_FIRST');
        return $root;
    }


    if($bid_paypassword==""){
        $root["show_err"] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
        $root["error_code"] = 2;
        return $root;
    }
    /*
        if(md5($bid_paypassword)!=$GLOBALS['user_info']['paypassword']){
            $root["show_err"] = $GLOBALS['lang']['PAYPASSWORD_ERROR'];
            $root["error_code"] = $GLOBALS['user_info'] ;
            return $ot;
        }
        /*
        if(!check_ipop_limit(CLIENT_IP,"deal_dobid",intval(app_conf("SUBMIT_DELAY"))))
        {
            $root["show_err"] =  $GLOBALS['lang']['SUBMIT_TOO_FAST'];
            return $root;
        }
        */

    $deal = get_deal($deal_id);
    if(!$deal){
        $root["show_err"] = $GLOBALS['lang']['PLEASE_SPEC_DEAL'];
        return $root;
    }

    if($deal['user_id'] == $GLOBALS['user_info']['id']){
        $root["show_err"] = $GLOBALS['lang']['CANT_BID_BY_YOURSELF'];
        return $root;
    }

    $root['ecv_money'] = 0;
    if(intval($use_interestrate) == 0)
    {
        if(intval($ecv_id) > 0){
            //红包抵用
            //$sql = "select * from ".DB_PREFIX."ecv as e left join ".DB_PREFIX."ecv_type as et on e.ecv_type_id = et.id where e.user_id = ".intval($GLOBALS['user_info']['id'])." AND e.id=".$ecv_id;
            $sql = "select * from ".DB_PREFIX."ecv as e where e.user_id = ".intval($GLOBALS['user_info']['id'])." AND e.id=".$ecv_id;
            $ecv = $GLOBALS['db']->getRow($sql);

            if(!$ecv){
                $root["show_err"] = "红包不存在";
                return $root;
            }
            if($ecv['use_limit'] > 0 && $ecv['use_limit'] - $ecv['use_count'] <=0 ){
                $root["show_err"] = "此红包已被使用过了";
                return $root;
            }
            if($ecv['begin_time'] > 0 && $ecv['begin_time'] > TIME_UTC){
                $root["show_err"] = "此红包还不能用";
                return $root;
            }
            if($ecv['end_time'] > 0 && ($ecv['end_time'] +24*3600 - 1) < TIME_UTC){
                $root["show_err"] = "此红包已过期";
                return $root;
            }
            $root['ecv_money'] = $ecv['money'];
        }
    }
    elseif(intval($use_interestrate) > 0 )
    {
        if(intval($interestrate_id) > 0){
            //加息券
            $i_sql = "select *,e.id as i_id from ".DB_PREFIX."interestrate as e left join ".DB_PREFIX."interestrate_type as et on e.ecv_type_id = et.id where ((e.user_id = ".intval($GLOBALS['user_info']['id'])." and e.to_user_id = 0) or e.to_user_id = ".intval($GLOBALS['user_info']['id']).") AND e.id=".$interestrate_id;

            //use_type = 0 PC端使用
            if($is_pc == 0)
            {
                $i_sql .= " and (et.use_type = 1 or et.use_type = 2)";
            }
            else
            {
                $i_sql .= " and (et.use_type = 0 or et.use_type = 2)";
            }

            $interestrate = $GLOBALS['db']->getRow($i_sql);

            if(!$interestrate){
                $root["show_err"] = "加息券不存在";
                return $root;
            }
            if($interestrate['use_limit'] > 0 && $interestrate['use_limit'] - $interestrate['use_count'] <=0 ){
                $root["show_err"] = "此加息券已被使用过了";
                return $root;
            }
            if($interestrate['begin_time'] > 0 && $interestrate['begin_time'] > TIME_UTC){
                $root["show_err"] = "此加息券还不能用";
                return $root;
            }
            if($interestrate['end_time'] > 0 && ($interestrate['end_time'] +24*3600 - 1) < TIME_UTC){
                $root["show_err"] = "此加息券已过期";
                return $root;
            }
            $root['interestrate_id'] = $interestrate['i_id'];
        }
    }

    if(intval($learn_id) > 0){
        //体验金抵用
        $today=to_date(TIME_UTC,"Y-m-d");
        $sql = "select lsl.* from ".DB_PREFIX."learn_send_list lsl left join ".DB_PREFIX."learn_type lt on lsl.type_id = lt.id where lt.invest_type = 1 and lt.is_effect = 1 AND lsl.is_recycle=0 AND lsl.user_id = ".intval($GLOBALS['user_info']['id'])." AND lsl.id=".$learn_id;
        $learn = $GLOBALS['db']->getRow($sql);

        if(!$learn){
            $root['show_err'] = "体验金不存在";
            return $root;
        }
        if($learn['is_use'] > 0){
            $root['show_err'] = "此体验金已被使用过了";
            return $root;
        }
        if($learn['begin_time'] > $today){
            $root['show_err'] = "此体验金还不能用";
            return $root;
        }
        if($learn['end_time'] < $today){
            $root['show_err'] = "此体验金已过期";
            return $root;
        }

        $root['learn_money'] = $learn['money'];
        $root['learn_id'] = $learn_id;

    }

    $deal = get_deal($deal_id);
    if(!$deal){
        $root["show_err"] = $GLOBALS['lang']['PLEASE_SPEC_DEAL'];
        return $root;
    }

    if($deal['user_id'] == $GLOBALS['user_info']['id']){
        $root["show_err"] = $GLOBALS['lang']['CANT_BID_BY_YOURSELF'];
        return $root;
    }

    if($deal['ips_bill_no']!="" && $GLOBALS['user_info']['ips_acct_no']==""){
        $root["show_err"] = "此标为第三方托管标，请先绑定第三方托管账户,<a href=\"".url("index","uc_center")."\" target='_blank'>点这里设置</a>";
        return $root;
    }

    //判断是否是新手专享
    if($deal['is_new']==1 &&  $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_load  WHERE user_id=".$GLOBALS['user_info']['id']." ") > 0){
        $root["show_err"] = "此标为新手专享标，您已经投过贷款了";
        return $root;
    }

    if($deal['is_wait'] == 1){
        $root["show_err"] = $GLOBALS['lang']['DEAL_IS_WAIT'];
        return $root;
    }


    if(floatval($deal['borrow_amount']) <= floatval($deal['load_money'])){
        $root["show_err"] = $GLOBALS['lang']['DEAL_BID_FULL'];
        return $root;
    }

    if(floatval($deal['deal_status']) != 1 ){
        $root["show_err"] = $GLOBALS['lang']['DEAL_FAILD_OPEN'];
        return $root;
    }


    //@file_put_contents("/Public/sqlog.txt",print_r($_REQUEST,1));
    //手机端或者 按份数 默认跑到这里
    if ($deal['uloadtype'] == 0 || $is_pc == 0){
        if(intval($bid_money) <=0 || intval(fmod(floatval($bid_money*100), 100))!=0){
            $root["show_err"] = $GLOBALS['lang']['BID_MONEY_NOT_TRUE'];
            //print_r($deal);
            return $root;
        }
        if($bid_money < $deal['min_loan_money']){
            $root["show_err"] = "最低投资金额：".$deal['min_loan_money'];
            //print_r($deal);
            return $root;
        }

        if($deal['uloadtype'] == 1 && $is_pc == 0 && ($bid_money % $deal['min_loan_money'])!=0){
            $root["show_err"] = "必须为".$deal['min_loan_money']."的倍数";
            //print_r($deal);
            return $root;
        }
        if(floatval($deal['max_loan_money']) >0){
            if($bid_money > floatval($deal['max_loan_money'])){
                $root["show_err"] = "最高投资金额：".$deal['max_loan_money'];
                //print_r($deal);
                /*
                 $root["bid_money"] = $bid_money;
                $root["max_loan_money"] = floatval($deal['max_loan_money']);
                $root["show_err"] = 'ddd2';
                print_r($root);
                die();
                */
                return $root;
            }
        }

        if((int)strim(app_conf('DEAL_BID_MULTIPLE')) > 0){
            if($bid_money%(int)strim(app_conf('DEAL_BID_MULTIPLE'))!=0){
                $root["show_err"] = $GLOBALS['lang']['BID_MONEY_NOT_TRUE'];
                $root["error_code"] = '212321312';
                return $root;
            }
        }


//		//判断所投的钱是否超过了剩余投标额度
//		if($bid_money > (round($deal['borrow_amount'],2) - round($deal['load_money'],2))){
//			$root["show_err"] = sprintf($GLOBALS['lang']['DEAL_LOAN_NOT_ENOUGHT'],format_price($deal['borrow_amount'] - $deal['load_money'] ));
//			return $root;
//		}
        //判断所投的钱是否超过了剩余投标额度
        if($bid_money > (round($deal['borrow_amount'],2) - round($deal['load_money'],2) - getCollWaitMoney($deal))){
            $root["show_err"] = sprintf($GLOBALS['lang']['DEAL_LOAN_NOT_ENOUGHT'],format_price($deal['borrow_amount'] - $deal['load_money'] - getCollWaitMoney($deal)));
            $root["error_code"] = '13232';
            return $root;
        }


        //判断所投的全部金额是否超过了所限制的金额
        if(floatval($deal['max_loan_money']) > 0){
            $has_bid_money = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_id." AND user_id=".$GLOBALS['user_info']['id']);
            if($has_bid_money > 0){
                if($has_bid_money > floatval($deal['max_loan_money'])){
                    $root["show_err"] = "您已经投满该借款所限制的额度：".format_price($deal['max_loan_money']);
                    return $root;
                }

                if($has_bid_money + $bid_money > floatval($deal['max_loan_money'])){
                    $root["show_err"] = "您已经投了".format_price($has_bid_money);
                    if(floatval($deal['max_loan_money']) - $has_bid_money > 0){
                        $root["show_err"] .= ",只能再投".format_price(floatval($deal['max_loan_money']) - $has_bid_money);
                    }
                    else{
                        $root["show_err"] .= ",不能再投了";
                    }
                    return $root;
                }
            }
        }

        $root["bid_money"] = $bid_money;
    }
    else{
        if(intval($bid_money) <=0 || intval(fmod(floatval($bid_money*100), 100))!=0){
            $root["show_err"] = $GLOBALS['lang']['BID_MONEY_NOT_TRUE'];
            $root["error_code"] = '2123213144442';
            //print_r($deal);
            return $root;
        }

        //判断所投的钱是否超过了剩余投标额度
        $has_bid_money = $GLOBALS['db']->getOne("SELECT sum(money) FROM ".DB_PREFIX."deal_load WHERE deal_id=".$deal_id." AND user_id=".$GLOBALS['user_info']['id']);
        $has_bid_portion = $has_bid_money/($deal['borrow_amount'] / $deal['portion']);
        if(intval($deal['max_portion']) > 0  && intval($bid_money) > (intval($deal['max_portion'] - intval($has_bid_portion)))){
            $root["show_err"] = "您已经购买了".$has_bid_portion."份，还能购买".intval($deal['max_portion'] - intval($has_bid_portion))."份";
            return $root;
        }
        elseif(intval($bid_money) > intval($deal['need_portion'])){
            $root["show_err"] = "您已经购买了".$has_bid_portion."份，还能购买".intval($deal['need_portion'])."份";
            return $root;
        }

        $root["bid_money"] = $bid_money * ($deal['borrow_amount'] / $deal['portion']);
    }

    if (!empty($deal['ips_bill_no'])){
        //第三方托管标
        if (!empty($GLOBALS['user_info']['ips_acct_no'])){
            $result = GetIpsUserMoney($GLOBALS['user_info']['id'],$GLOBALS['user_info']['user_type']);
            if((floatval($result['pBalance']) + floatval($root['ecv_money'])) < $root["bid_money"]){
                $root["status"] = 0;
                $root["show_err"] = "资金不足，请先充值";
                return $root;
            }
        }
    }

    $root["deal"] = $deal;
    if($deal['ips_bill_no']==""){
        $root["status"] = 1;//0:出错;1:正确;
        $root["error_code"] = '21232131144442';
        return $root;
    }
    else{
        $root["status"] = 2;//第三方托管标 正确 21232513144442
        $root["error_code"] = '21232513144442';
        return $root;
    }

}

function dobid2_ok($deal_id,$user_id){
    $deal = get_deal($deal_id);
    sys_user_status($user_id);
    //超过一半的时候

    if($deal['deal_status']==1 && $deal['progress_point'] >= 50 && $deal['progress_point']<=60 && $deal['is_send_half_msg'] == 0)
    {
        $msg_conf = get_user_msg_conf($deal['user_id']);
        //邮件
        if(app_conf("MAIL_ON")){
            if(!$msg_conf || intval($msg_conf['mail_half'])==1){
                $load_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_HALF_EMAIL'",false);
                $user_info = get_user_info("AES_DECRYPT(email_encrypt,'".AES_DECRYPT_KEY."') as email,user_name","id = ".$deal['user_id']);
                $tmpl_content = $load_tmpl['content'];
                $notice['user_name'] = $user_info['user_name'];
                $notice['deal_name'] = $deal['name'];
                $notice['deal_url'] = SITE_DOMAIN.$deal['url'];
                $notice['site_name'] = app_conf("SHOP_TITLE");
                $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
                $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
                $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");


                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = "您的借款列表“".$deal['name']."”招标过半！";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = TIME_UTC;
                $msg_data['user_id'] =  $deal['user_id'];
                $msg_data['is_html'] = $load_tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }

        //站内信
        if(intval($msg_conf['sms_half'])==1){

            $notices['shop_title'] = app_conf("SHOP_TITLE");
            $notices['url'] =  "“<a href=\"".$deal['url']."\">".$deal['name']."</a>”";

            $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_OVER_FIVE'",false);
            $GLOBALS['tmpl']->assign("notice",$notices);
            $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);
            send_user_msg("",$content,0,$deal['user_id'],TIME_UTC,0,true,15);
        }

        //更新
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal",array("is_send_half_msg"=>1),"UPDATE","id=".$deal_id);
    }
}

function dobid2($deal_id,$bid_money,$bid_paypassword,$is_pc=0,$ecv_id=0,$learn_id=0,$interestrate_id=0,$use_interestrate=0){
    $root = check_dobid2($deal_id,$bid_money,$bid_paypassword,$is_pc,$ecv_id,$learn_id,$interestrate_id,$use_interestrate);


    //$root["status"] = 0;
    $bid_money = floatval($root['bid_money']);
    $bid_paypassword = strim($bid_paypassword);
    //余额获取余额
    if($GLOBALS['user_info']['id'] == 100000){
        $result_remain_money['pBalance'] = 1000;
    }else{
        $result_remain_money['pBalance'] = GetIpsUserMoney($GLOBALS['user_info']['id'],0);
    }


    if($bid_money - floatval($root['ecv_money']) - floatval($root['learn_money']) > $result_remain_money['pBalance']){
        $root["show_err"] = '您的余额不足了';//$GLOBALS['lang']['MONEY_NOT_ENOUGHT'];
        $root['error_code'] = $GLOBALS['user_info']['money'];
        return $root;
    }

    $data['user_id'] = $GLOBALS['user_info']['id'];
    $data['user_name'] = $GLOBALS['user_info']['user_name'];
    $data['deal_id'] = $deal_id;
    $data['money'] = $bid_money;

    if(intval($use_interestrate)==0)
    {
        $data['ecv_id'] = $ecv_id;
        $data['interestrate_id'] = 0;
        $interestrate_id=0;
    }
    else
    {
        $data['ecv_id'] = 0;
        $ecv_id = 0;
        $data['interestrate_id'] = $interestrate_id;
    }

    $data['learn_money'] = $root['learn_money'];
    $data['learn_id'] = $root['learn_id'];
    $data['has_auth'] = 0;

    $insertdata = return_deal_load_data($data,$GLOBALS['user_info'],$root['deal']);

    //$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal SET load_money=load_money+".$insertdata['money']." WHERE load_money+".$insertdata['money']."<= borrow_amount AND id=".$deal_id);


    $load_id = 0;//$GLOBALS['db']->affected_rows() > 0
    if(true){
        $root['error_code'] = '124';
        //$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$insertdata,"INSERT");
        $load_id = 1 ;//$GLOBALS['db']->insert_id();
    }

    //$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$insertdata,"INSERT");
    //$load_id = $GLOBALS['db']->insert_id();
    if($load_id > 0){
        //更改红包
        $ecv_money = 0;
        if($ecv_id > 0){
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv SET use_count = use_count + 1 WHERE (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND id=".$ecv_id." AND user_id=".$GLOBALS['user_info']['id']);
            if(true){
                $ecv_money = $GLOBALS['db']->getOne("SELECT `money` FROM ".DB_PREFIX."ecv WHERE id=".$ecv_id);
            }
        }
        //更改加息券状态
        if($interestrate_id > 0){
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate SET use_count = use_count + 1 WHERE (begin_time =0 OR (begin_time > 0 AND begin_time < ".TIME_UTC.")) AND (end_time = 0 OR (end_time > 0  AND (end_time +24*3600 - 1) > ".TIME_UTC.")) AND (use_limit =0  OR (use_limit >0 AND use_limit - use_count > 0)) AND id=".$interestrate_id." AND ((user_id=".$GLOBALS['user_info']['id'].") or to_user_id = ".$GLOBALS['user_info']['id'].")");
        }

        //更改体验金状态
        if($learn_id > 0){
            $now_time = to_date(TIME_UTC,"Y-m-d H:i:s");
            $today = to_date(TIME_UTC,"Y-m-d");
            $GLOBALS['db']->query("update ".DB_PREFIX."learn_send_list set is_use = '1',use_time ='".$now_time."',use_date='".$today."' where is_use = '0' and id ='".$learn_id."' and  user_id = ".intval($GLOBALS['user_info']['id'])." ");
        }
        //更改资金记录
        if($bid_money - $ecv_money - $insertdata['learn_money'] > 0){

            $msg = '[<a href="'.$root['deal']['url'].'" target="_blank">'.$root['deal']['name'].'</a>]的投标,付款单号'.$load_id;
            require_once APP_ROOT_PATH."system/libs/user.php";
            modify_account(array('money'=>-($bid_money - $ecv_money - $insertdata['learn_money']),'lock_money'=>($bid_money - $ecv_money-$insertdata['learn_money'])),$GLOBALS['user_info']['id'],$msg,2);

        }

        dobid2_ok($deal_id,$GLOBALS['user_info']['id']);

        if(app_conf('SMS_ON')==1 && app_conf('SMS_DEAL_LOAD')==1){
            //发送投标短信
            $load_tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_DEAL_LOAD'",false);
            $tmpl_content = $load_tmpl['content'];
            $notice['user_name'] = $GLOBALS['user_info']['user_name'];
            $notice['deal_name'] = $root['deal']['name'];
            $notice['money'] = number_format($bid_money);
            $notice['time'] = to_date(TIME_UTC,"Y年m月d日 H:i");
            $notice['site_name'] = app_conf("SHOP_TITLE");

            $GLOBALS['tmpl']->assign("notice",$notice);

            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
            $msg_data['dest'] = $GLOBALS['user_info']['mobile'];
            $msg_data['send_type'] = 0;
            $msg_data['title'] = $root['deal']['name']."投标短信通知";
            $msg_data['content'] = addslashes($msg);
            $msg_data['send_time'] = 0;
            $msg_data['is_send'] = 0;
            $msg_data['create_time'] = TIME_UTC;
            $msg_data['user_id'] =  $GLOBALS['user_info']['id'];
            $msg_data['is_html'] = $load_tmpl['is_html'];
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        }
        $root["show_err"] = '余额不正确或者密码不正确';
        //$root["show_err"] = $GLOBALS['lang']['ERROR_TITLE'];
        //$root["status"] = 1;//0:出错;1:正确;
        //return $root;
        //showSuccess($GLOBALS['lang']['DEAL_BID_SUCCESS'],$ajax,url("index","deal",array("id"=>$id)));
    }
    else{
        $root["show_err"] = 'title';//$GLOBALS['lang']['ERROR_TITLE'];
        return $root;
    }
    if ($root["status"] == 0){
        return $root;
    }
    elseif($root["status"] == 2){
        $root['jump'] = "http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterCreditorPage&deal_id=$deal_id&user_id=".$GLOBALS['user_info']['id']."&bid_money=".$root['bid_money']."&bid_paypassword=$bid_paypassword"."&from=".$GLOBALS['request']['from']."&learn_id=".$learn_id."&ecv_id=".$ecv_id."&use_interestrate=".$use_interestrate."&interestrate_id=".$interestrate_id;
        //$root['jump'] = str_replace(array("/mapi","/wap"), "", SITE_DOMAIN.$root['jump']);
        return $root;
    }else{
        $root["show_err"] = 'here';
        return $root;
    }
}



function get_transfer($union_sql,$condition){

    $sql = 'SELECT dlt.id,dlt.transfer_amount,dlt.near_repay_time,dlt.user_id,d.loantype,d.next_repay_time,d.last_repay_time,d.rate,d.repay_start_time,d.repay_time,dlt.load_money,d.name as deal_name,dlt.load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time,dlt.transfer_time,dlt.load_id,d.tcontract_id,d.user_load_transfer_fee,d.user_id as duser_id FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $transfer = $GLOBALS['db']->getRow($sql);

    if($transfer){
        //下个还款日
        $transfer['next_repay_time_format'] = to_date($transfer['next_repay_time'],"Y-m-d");
        $transfer['near_repay_time_format'] = to_date(next_replay_month($transfer['near_repay_time']," -1 "),"Y 年 m 月 d 日");

        //什么时候开始借
        $transfer['repay_start_time_format']  = to_date($transfer['repay_start_time'],"Y 年 m 月 d 日");

        //还款日
        $transfer['final_repay_time'] = next_replay_month($transfer['repay_start_time'],$transfer['repay_time']);
        $transfer['final_repay_time_format'] = to_date($transfer['final_repay_time'],"Y-m-d");
        //剩余期数
        if(is_last_repay($transfer['loantype'])==1)
            $transfer['how_much_month'] = $transfer['repay_time'];
        else
            $transfer['how_much_month'] = how_much_month($transfer['near_repay_time'],$transfer['final_repay_time']);

        if(is_last_repay($transfer['loantype'])==2){
            $transfer['how_much_month'] =  $transfer['how_much_month'] / 3 ;
        }

        $transfer_rs = deal_transfer($transfer);

        $transfer['month_repay_money'] = $transfer_rs['month_repay_money'];
        $transfer['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
        $transfer['left_benjin'] = $transfer_rs['left_benjin'];

        $transfer['month_repay_money_format'] = format_price($transfer['month_repay_money']);

        $transfer['all_must_repay_money_format'] = format_price($transfer['all_must_repay_money']);

        $transfer['left_benjin_format'] = format_price($transfer['left_benjin']);
        //剩多少利息
        $transfer['left_lixi'] = $transfer['all_must_repay_money'] - $transfer['left_benjin'];
        $transfer['left_lixi_format'] = format_price($transfer['left_lixi']);

        //转让价格
        $transfer['transfer_amount_format'] =  format_price($transfer['transfer_amount']);

        //投标价格
        $transfer['load_money_format'] =  format_price($transfer['load_money']);

        //转让管理费
        $transfer['transfer_fee_format'] = format_price($transfer['transfer_amount']*(float)$transfer["user_load_transfer_fee"]*0.01);

        //转让收益
        $transfer['transfer_income_format'] =  format_price($transfer['all_must_repay_money']-$transfer['transfer_amount']);

        if($transfer['tras_create_time'] !=""){
            $transfer['tras_create_time_format'] =  to_date($transfer['tras_create_time'],"Y-m-d");
        }

        if(intval($transfer['transfer_time'])>0){
            $transfer['transfer_time_format'] =  to_date($transfer['transfer_time'],"Y-m-d");
        }

        if($transfer['tras_create_time'] !=""){
            $transfer['tras_create_time_format'] =  to_date($transfer['tras_create_time'],"Y 年 m 月 d 日");
        }

        $transfer['transfer_time_format'] =  to_date($transfer['transfer_time'],"Y 年 m 月 d 日");

        $transfer['user'] = get_user("*",$transfer['user_id']);
        if($transfer['t_user_id'] > 0)
            $transfer['tuser'] = get_user("*",$transfer['t_user_id']);

        $transfer['duser'] = get_user("*",$transfer['duser_id']);

        $transfer['remain_time'] =next_replay_month($transfer['near_repay_time']) - TIME_UTC + 24*3600 - 1;
        $transfer['remain_time_format'] = remain_time($transfer['remain_time']);

        if(is_last_repay($transfer['loantype'])==2){
            $transfer['repay_time'] =  $transfer['repay_time'] / 3 ;
        }

        $transfer['url'] = url("index","transfer#detail",array("id"=>$transfer['id']));
    }

    return $transfer;

}

function get_transfer_list($limit,$condition='',$extfield,$union_sql,$orderby = ''){
    //获取转让列表
    $count_sql = 'SELECT count(dlt.id) FROM '.DB_PREFIX.'deal_load_transfer dlt LEFT JOIN '.DB_PREFIX.'deal d ON d.id =dlt.deal_id WHERE  d.is_effect=1 AND d.is_delete = 0 '.$condition;

    $rs_count = $GLOBALS['db']->getOne($count_sql);

    if($rs_count > 0){
        $list_sql = 'SELECT dlt.*,d.loantype,d.name,d.icon,d.cate_id,d.user_id as duser_id,d.rate,d.last_repay_time,d.repay_start_time,d.repay_time,d.repay_time_type '.$extfield.'  FROM '.DB_PREFIX.'deal_load_transfer dlt LEFT JOIN '.DB_PREFIX.'deal d ON d.id =dlt.deal_id '.$union_sql.' WHERE d.is_effect=1 AND d.is_delete = 0 '.$condition;
        $list_sql .= ' ORDER BY '.$orderby;
        $list_sql .=' LIMIT '.$limit;

        $list = $GLOBALS['db']->getAll($list_sql);
        foreach($list as $k=>$v){
            $list[$k]['duser'] = get_user("*",$v['duser_id']);
            $list[$k]['user'] = get_user("*",$v['user_id']);
            if($v['t_user_id'] > 0)
                $list[$k]['tuser'] = get_user("*",$v['t_user_id']);
            else
                $list[$k]['tuser'] = null;


            if($list[$k]['tuser'] === false){
                $list[$k]['tuser'] = null;
            }

            if($list[$k]['duser'] === false){
                $list[$k]['duser'] = null;
            }

            if($list[$k]['user'] === false){
                $list[$k]['user'] = null;//new ArrayObject(); {}
            }


            $list[$k]['url'] = url("index","transfer#detail",array("id"=>$v['id']));
            //$deal['url'] = $durl;
            //x	$durl = "/index.php?ctl=deal&act=mobile&id=".$v['deal_id'];
            $durl = APP_ROOT."/wap/index.php?ctl=transfer_mobile&is_sj=1&id=".$v['deal_id']."&transfer_id=".$v['id'];
            $list[$k]['app_url'] = str_replace(array("/mapi","/wap"), "", SITE_DOMAIN.$durl);


            //剩余期数
            $list[$k]['final_repay_time'] = $v['final_repay_time'] = next_replay_month($v['repay_start_time'],$v['repay_time']);

            $list[$k]['final_repay_time_format'] = to_date($v['final_repay_time'],"Y-m-d");

            if(is_last_repay($v['loantype'])==1)
                $list[$k]['how_much_month'] = $v['repay_time'];
            else
                $list[$k]['how_much_month'] = how_much_month($v['near_repay_time'],$v['final_repay_time']);

            if(is_last_repay($v['loantype'])==2) {
                $list[$k]['how_much_month'] = $list[$k]['how_much_month']/3;
            }

            if($v['cate_id'] > 0){
                $list[$k]['cate_info'] = $GLOBALS['db']->getRow("select id,name,brief,uname,icon from ".DB_PREFIX."deal_cate where id = ".$v['cate_id']." and is_effect = 1 and is_delete = 0",false);
            }

            $transfer_rs = deal_transfer($list[$k]);
            $list[$k]['month_repay_money'] = $transfer_rs['month_repay_money'];
            $list[$k]['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
            $list[$k]['left_benjin'] = $transfer_rs['left_benjin'];


            if($list[$k]['left_benjin'] < 100)
                $list[$k]['left_benjin_format'] = format_price($list[$k]['left_benjin']);
            else
                $list[$k]['left_benjin_format'] = format_price($list[$k]['left_benjin']/10000)."万";

            //剩多少利息
            $list[$k]['left_lixi'] = $list[$k]['all_must_repay_money'] - $list[$k]['left_benjin'];

            if($list[$k]['left_lixi'] < 100)
                $list[$k]['left_lixi_format'] = format_price($list[$k]['left_lixi']);
            else
                $list[$k]['left_lixi_format'] = format_price($list[$k]['left_lixi']/10000)."万";

            $list[$k]['remain_time'] = next_replay_month($v['near_repay_time']) - TIME_UTC + 24*3600 - 1;
            $list[$k]['remain_time_format'] = remain_time($list[$k]['remain_time']);


            $list[$k]['near_repay_time_format'] = to_date($v['near_repay_time'],"Y-m-d");
            if($v['transfer_amount'] < 100)
                $list[$k]['transfer_amount_format'] = format_price($v['transfer_amount']);
            else
                $list[$k]['transfer_amount_format'] = format_price($v['transfer_amount']/10000)."万";

            //转让收益
            $list[$k]['transfer_income'] =  $list[$k]['all_must_repay_money']-$list[$k]['transfer_amount'];
            $list[$k]['transfer_income_format'] =  format_price($list[$k]['transfer_income']);

            //
            $list[$k]['transfer_time_format'] = to_date($v['transfer_time'],"Y-m-d");
            if(is_last_repay($v['loantype'])==2) {
                $list[$k]['repay_time'] = $list[$k]['repay_time']/3;
            }
        }

        $result["list"] =  $list;
    }
    $result["rs_count"] =  $rs_count;
    return $result;
}


//正常还款执行界面
function getUcRepayBorrowMoney($id,$ids,$user_id=0){
    $id = intval($id);
    $root = array();
    $root["status"] = 0;//0:出错;1:正确;

    if($id == 0){
        $root["show_err"] = "操作失败！";
        return $root;
    }

    $deal = get_deal($id);
    if(!$deal)
    {
        $root["show_err"] = "借款不存在！";
        return $root;
    }
    if($deal['ips_bill_no']!=""){
        $root["status"] = 2;
        $root["jump"] = APP_ROOT.'/index.php?ctl=collocation&act=RepaymentNewTrade&deal_id='.$deal['id'].'&l_key='.$ids."&from=".$GLOBALS['request']['from'];
        $root['jump'] = str_replace(array("/mapi","/wap"), "", SITE_DOMAIN.$root['jump']);
        return $root;
    }

    if($user_id > 0){
        $GLOBALS['user_info'] = get_user("*",$user_id);
    }

    if($deal['user_id']!=$GLOBALS['user_info']['id']){
        $root["show_err"] = "不属于你的借款！";
        return $root;
    }
    if($deal['deal_status']!=4){
        $root["show_err"] = "借款不是还款状态！";
        return $root;
    }

    $ids = explode(",",$ids);

    //当前用户余额
    $user_total_money = (float)$GLOBALS['user_info']['money'];

    if($user_total_money<= 0){
        $root["show_err"] = "余额不足";
        return $root;
    }

    $last_repay_key = -1;
    require_once APP_ROOT_PATH.'system/libs/user.php';

    foreach($ids as $lkey){
        //还了多少人
        $repay_user_count = 0;
        //多少人未还
        $no_repay_user_count =0;
        //还了多少本息
        $repay_money = 0;
        //还了多少逾期罚息
        $repay_impose_money = 0;
        //还了多少管理费
        $repay_manage_money = 0;
        //还了多少抵押管理费
        $mortgage_fee = 0;
        //还了多少逾期管理费
        $repay_manage_impose_money = 0;

        //用户回款 get_deal_user_load_list($deal_info, $user_id = 0 ,$lkey = -1 , $ukey = -1,$true_time=0,$get_type = 0, $r_type = 0, $limit = "")
        $user_loan_list = get_deal_user_load_list($deal, 0 , $lkey , -1 , 0 , 1);
        //如果已收取管理费
        $get_manage = $GLOBALS['db']->getOne("SELECT get_manage FROM ".DB_PREFIX."deal_repay WHERE deal_id = ".$deal['id']." and l_key=".$lkey."  ");

        //===============还款================
        foreach($user_loan_list as $lllk=>$lllv){
            foreach($lllv as $kk=>$vv){
                if($vv['has_repay']==0 ){//借入者已还款，但是没打款到借出用户中心
                    $user_load_data = array();

                    $user_load_data['true_repay_time'] = TIME_UTC;
                    $user_load_data['true_repay_date'] = to_date(TIME_UTC);
                    $user_load_data['is_site_repay'] = 0;
                    $user_load_data['status'] = 0;

                    $user_load_data['true_repay_money'] = (float)$vv['month_repay_money'];
                    $user_load_data['true_self_money'] = (float)$vv['self_money'];
                    $user_load_data['true_interest_money'] = (float)$vv['interest_money'];
                    $user_load_data['true_manage_money'] = (float)$vv['manage_money'];
                    $user_load_data['true_manage_interest_money'] = (float)$vv['manage_interest_money'];
                    $user_load_data['true_repay_manage_money'] = (float)$vv['repay_manage_money'];
                    $user_load_data['true_manage_interest_money_rebate'] = (float)$vv['manage_interest_money_rebate'];
                    $user_load_data['impose_money'] = (float)$vv['impose_money'];
                    $user_load_data['repay_manage_impose_money'] = (float)$vv['repay_manage_impose_money'];
                    $user_load_data['true_reward_money'] = (float)$vv['reward_money'];
                    $user_load_data['true_mortgage_fee'] = (float)$vv['mortgage_fee'];

                    $need_repay_money = 0;
                    if($get_manage==0)
                        $need_repay_money += $user_load_data['true_repay_money']  + $user_load_data['impose_money'] + $user_load_data['true_repay_manage_money'] + $user_load_data['repay_manage_impose_money'] + $user_load_data['mortgage_fee'];
                    else
                        $need_repay_money += $user_load_data['true_repay_money']  + $user_load_data['impose_money'] + $user_load_data['repay_manage_impose_money'] + $user_load_data['mortgage_fee'];
                    //=============余额足够才进行还款=================
                    if((float)$need_repay_money <= $user_total_money){

                        if($vv['status']>0)
                            $user_load_data['status'] = $vv['status'] - 1;

                        $user_load_data['has_repay'] = 1;
                        if($get_manage == 1){
                            unset($user_load_data['true_repay_manage_money']);
                        }
                        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$user_load_data,"UPDATE","id=".$vv['id']."  AND has_repay = 0  ","SILENT");

                        if($GLOBALS['db']->affected_rows() > 0){

                            $last_repay_key = $lkey;
                            $repay_user_count +=1;
                            $repay_money +=$user_load_data['true_repay_money'];
                            $repay_impose_money += $user_load_data['impose_money'];
                            $repay_manage_money += $user_load_data['true_repay_manage_money'];
                            $repay_manage_impose_money += $user_load_data['repay_manage_impose_money'];
                            $user_total_money = $user_total_money - $need_repay_money;
                            $mortgage_fee+= $user_load_data['true_mortgage_fee'];

                            $unext_loan = $user_loan_list[$vv['u_key']][$kk+1];


                            $load_repay_rs = $GLOBALS['db']->getRow("SELECT (sum(true_interest_money) + sum(impose_money)) as shouyi,sum(impose_money) as total_impose_money FROM ".DB_PREFIX."deal_load_repay WHERE deal_id=".$deal['id']." AND user_id=".$vv['user_id']);
                            $all_shouyi_money= number_format($load_repay_rs['shouyi'],2);
                            $all_impose_money = number_format($load_repay_rs['total_impose_money'],2);
                            //$notices['content'] = "本次投标共获得收益:".$all_shouyi_money."元,其中违约金为:".$all_impose_money."元,本次投标已回款完毕！";


                            if($user_load_data['impose_money'] !=0 || $user_load_data['true_manage_money'] !=0 || $user_load_data['true_repay_money']!=0){
                                $in_user_id  = $vv['user_id'];
                                //如果是转让债权那么将回款打入转让者的账户
                                if((int)$vv['t_user_id']== 0){
                                    $loan_user_info['user_name'] = $vv['user_name'];
                                    $loan_user_info['email'] = $vv['email'];
                                    $loan_user_info['mobile'] = $vv['mobile'];
                                }
                                else{
                                    $in_user_id = $vv['t_user_id'];
                                    $loan_user_info['user_name'] = $vv['t_user_name'];
                                    $loan_user_info['email'] = $vv['t_email'];
                                    $loan_user_info['mobile'] = $vv['t_mobile'];
                                }

                                //更新用户账户资金记录
                                modify_account(array("money"=>$user_load_data['true_repay_money']),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,回报本息",5);

                                if($user_load_data['true_manage_money'] > 0)
                                    modify_account(array("money"=>-$user_load_data['true_manage_money']),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,投标管理费",20);

                                //利息管理费
                                modify_account(array("money"=>-$user_load_data['true_manage_interest_money']),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,投标利息管理费",20);

                                if($user_load_data['impose_money'] != 0)
                                    modify_account(array("money"=>$user_load_data['impose_money']),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期罚息",21);

                                //投资者奖励
                                if($user_load_data['true_reward_money']!=0){
                                    modify_account(array("money"=>$user_load_data['true_reward_money']),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,奖励收益",28);
                                }

                                //扣除体验金
                                if($vv['learn_id'] > 0){
                                    $load_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_load where id=".$vv['load_id']);
                                    if($load_info){
                                        //还需回收多少
                                        $back_learn_money = 0;
                                        if(floatval($load_info['learn_money']) > floatval($load_info['back_learn_money'])){
                                            $back_learn_money = floatval($load_info['learn_money']) - floatval($load_info['back_learn_money']);
                                        }
                                        if($back_learn_money > 0){
                                            if(($user_load_data['true_repay_money'] -$user_load_data['true_manage_money'] -$user_load_data['true_manage_interest_money'] + $user_load_data['impose_money'] + $user_load_data['true_reward_money']) >= $back_learn_money){
                                                modify_account(array("money"=>-$back_learn_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,体验金回收",54);
                                            }
                                            else{
                                                $back_learn_money = $user_load_data['true_repay_money'] -$user_load_data['true_manage_money'] -$user_load_data['true_manage_interest_money'] + $user_load_data['impose_money'] + $user_load_data['true_reward_money'];
                                                modify_account(array("money"=>-$back_learn_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,体验金回收",54);
                                            }

                                            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET  back_learn_money = back_learn_money + ".$back_learn_money." where id=".$vv['load_id']);
                                        }
                                    }
                                }

                                //普通会员邀请返利
                                get_referrals($vv['id']);

                                //投资者返佣金
                                if($user_load_data['true_manage_interest_money_rebate'] !=0){
                                    /*ok*/
                                    $reback_memo = sprintf($GLOBALS['lang']["INVEST_REBATE_LOG"],$deal["url"],$deal["name"],$loan_user_info["user_name"],intval($vv["l_key"])+1);
                                    reback_rebate_money($in_user_id,$user_load_data['true_manage_interest_money_rebate'],"invest",$reback_memo);
                                }


                                //短信通知回款
                                $loan_user_info['id'] = $in_user_id;
                                send_repay_reback_sms_mail($deal,$loan_user_info,$unext_loan,$user_load_data,$all_shouyi_money,$all_impose_money);




                            }
                        }
                    }

                    //=============余额足够才进行还款=================

                }
            }
        }
        //===============还款================

        if($repay_user_count > 0){
            //判断当前期是否还款完毕
            $true_repay_count = $GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_load_repay WHERE deal_id = ".$deal['id']." and l_key=".$lkey." AND has_repay=1 ");

            $ext_str= "";
            if($true_repay_count<>$repay_user_count){
                $ext_str="[部分]";
            }
            //更新用户账户资金记录
            modify_account(array("money"=>-$repay_money),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,偿还本息$ext_str",4);
            if($repay_impose_money!=0)
                modify_account(array("money"=>-$repay_impose_money),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期罚息$ext_str",11);

            if($repay_manage_money > 0 && $get_manage == 0)
                modify_account(array("money"=>-$repay_manage_money),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,借款管理费$ext_str",10);

            if($mortgage_fee > 0)
                modify_account(array("money"=>-$mortgage_fee),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,抵押物管理费$ext_str",27);

            if($repay_manage_impose_money!=0 )
                modify_account(array("money"=>-$repay_manage_impose_money),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期管理费$ext_str",12);

            $rebate_rs = get_rebate_fee($GLOBALS['user_info']['id'],"borrow");
            $true_manage_money_rebate = $repay_manage_money* floatval($rebate_rs['rebate'])/100;
            //借款者返佣
            if($true_manage_money_rebate!=0){
                /*ok*/
                $reback_memo = sprintf($GLOBALS['lang']["BORROW_REBATE_LOG"],$deal["url"],$deal["name"],$deal["user"]["user_name"],intval($kk)+1);
                reback_rebate_money($GLOBALS['user_info']['id'],$true_manage_money_rebate,"borrow",$reback_memo);
            }
        }

        $r_msg = "会员还款$ext_str";
        if($repay_money > 0){
            $r_msg .=",本息：".format_price($repay_money);
        }
        if($repay_impose_money> 0){
            $r_msg .=",逾期费用：".format_price($repay_impose_money);
        }
        if($repay_manage_money > 0 && $get_manage == 0){
            $r_msg .=",管理费：".format_price($repay_manage_money);
        }
        if($mortgage_fee > 0){
            $r_msg .=",抵押物管理费：".format_price($mortgage_fee);
        }
        if($repay_manage_impose_money > 0){
            $r_msg .=",逾期管理费：".format_price($repay_manage_impose_money);
        }
        $repay_id = $GLOBALS['db']->getOne("SELECT id  FROM ".DB_PREFIX."deal_repay WHERE deal_id = ".$deal['id']." and l_key=".$lkey);
        repay_log($repay_id,$r_msg,$GLOBALS['user_info']['id'],0);


        //$content = "您好，您在".app_conf("SHOP_TITLE")."的借款 “<a href=\"".$deal['url']."\">".$deal['name']."</a>”的借款第".($lkey+1)."期还款".number_format(($repay_money+$repay_impose_money+$repay_manage_money+$repay_manage_impose_money),2)."元，";
        //如果还款完毕
        $sms_ext_str = "成功";
        if($left_user_count = $GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_load_repay WHERE deal_id = ".$deal['id']." and l_key=".$lkey." AND has_repay = 0 ") == 0){
            //$content .="本期还款完毕。";
            $notices['repay_status'] = "本期还款完毕";
            $impose_rs = $GLOBALS['db']->getRow("SELECT sum(true_self_money) as total_self_money,sum(true_interest_money) as total_interest_money,sum(true_repay_money) as total_repay_money,sum(impose_money) as total_impose_money,sum(true_repay_manage_money) as total_repay_manage_money,sum(repay_manage_impose_money) as total_repay_manage_impose_money,sum(true_mortgage_fee) as total_mortgage_fee  FROM ".DB_PREFIX."deal_load_repay WHERE deal_id = ".$deal['id']." and l_key=".$lkey." AND has_repay = 1");
            //判断是否逾期
            $repay_update_data['has_repay'] = 1;
            $repay_update_data['true_repay_time'] = TIME_UTC;
            $repay_update_data['true_repay_date'] = to_date(TIME_UTC);
            $repay_update_data['true_repay_money'] = floatval($impose_rs['total_repay_money']);
            $repay_update_data['true_self_money'] =  floatval($impose_rs['total_self_money']);
            $repay_update_data['true_interest_money'] =  floatval($impose_rs['total_interest_money']);
            $repay_update_data['impose_money'] =floatval($impose_rs['total_impose_money']);
            if($get_manage == 0){
                $repay_update_data['true_manage_money'] =floatval($impose_rs['total_repay_manage_money']);
            }

            $repay_update_data['true_mortgage_fee'] =floatval($impose_rs['total_mortgage_fee']);

            $repay_update_data['manage_impose_money']=floatval($impose_rs['total_repay_manage_impose_money']);

            //返佣金额
            $rebate_rs = get_rebate_fee($GLOBALS['user_info']['id'],"borrow");
            $repay_update_data['true_manage_money_rebate'] =floatval($impose_rs['total_repay_manage_money']) * floatval($rebate_rs['rebate'])/100;

            if($vv['impose_day'] > 0){

                //VIP降级-逾期还款
                $type = 2;
                $type_info = 5;
                $resultdate = syn_user_vip($GLOBALS['user_info']['id'],$type,$type_info);

                if($vv['impose_day'] < app_conf('YZ_IMPSE_DAY')){
                    modify_account(array("point"=>trim(app_conf('IMPOSE_POINT'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期还款",11);
                    $repay_update_data['status'] = 2;
                }
                else{
                    modify_account(array("point"=>trim(app_conf('YZ_IMPOSE_POINT'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,严重逾期",11);
                    $repay_update_data['status'] = 3;
                }
            }
            elseif(TIME_UTC<=((int)$vv['repay_day'] + 24*3600-1)){
                $repay_update_data['status'] = 1;

                //VIP升级 -正常还款
                $type = 1;
                $type_info = 3;
                $resultdate = syn_user_vip($GLOBALS['user_info']['id'],$type,$type_info);
            }

            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$repay_update_data,"UPDATE","deal_id = ".$deal['id']." and l_key=".$lkey);

            $notices['has_next_loan'] = 0;
            if($next_loan =$GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." and l_key > ".$last_repay_key." ORDER BY  l_key ASC")){
                //$content .= "本笔借款的下个还款日为".to_date($next_loan['repay_day'],"Y年m月d日")."，需要本息".number_format($next_loan['repay_money'],2)."元。";
                $notices['has_next_loan'] = 1;
                $notices['next_repay_time'] = to_date($next_loan['repay_time'],"Y年m月d日");
                $notices['next_repay_money'] = number_format($next_loan['repay_money'],2);
            }
        }
        elseif($repay_user_count > 0){
            //$content .="本期部分还款，还有".$left_user_count."个投资人待还。";
            $notices['repay_status'] = "本期部分还款";
            $notices['left_user_count'] = $left_user_count;
            $sms_ext_str = "部分";
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_repay SET has_repay = 2 WHERE deal_id = ".$deal['id']." and l_key=".$lkey);
        }

        //您好，您在{$notice.shop_title}的借款{$notice.url}的借款第{$notice.key}期还款{$notice.money}元

        $notices['site_title'] = app_conf("SHOP_TITLE");
        $notices['url'] =  "“<a href=\"".$deal['url']."\">".$deal['name']."</a>”";
        $notices['index'] =  ($lkey+1);
        $notices['repay_money'] = ($repay_money+$repay_impose_money+$repay_manage_impose_money);
        if($get_manage == 0){
            $notices['repay_money'] = number_format($notices['repay_money'] + $repay_manage_money,2);
        }
        else{
            $notices['repay_money'] = number_format($notices['repay_money'],2);
        }

        $notices['repay_money'] += $mortgage_fee;

        $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_REPAY_MONEY_MSG'",false);
        $GLOBALS['tmpl']->assign("notice",$notices);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);

        send_user_msg("",$content,0,$GLOBALS['user_info']['id'],TIME_UTC,0,true,8);
        unset($notices);

        //短信通知
        if(app_conf("SMS_ON")==1&&app_conf('SMS_SEND_REPAY')==1){
            $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_REPAY_SUCCESS_MSG'",false);
            $tmpl_content = $tmpl['content'];
            //$sms_content = "尊敬的".app_conf("SHOP_TITLE")."用户".$GLOBALS['user_info']['user_name']."，您的借款“".$deal['name']."”第".($lkey+1)."期".$sms_ext_str."还款".number_format(($repay_money+$repay_impose_money+$repay_manage_money+$repay_manage_impose_money),2)."元，感谢您的关注和支持。";
            $notice['user_name'] = $GLOBALS['user_info']['user_name'];
            $notice['deal_name'] = $deal['sub_name'];
            $notice['site_name'] = app_conf("SHOP_TITLE");
            $notice['index'] = $lkey+1;
            $notice['status'] = $sms_ext_str;
            if($get_manage ==0){
                $notice['all_money'] = number_format(($repay_money+$repay_impose_money+$repay_manage_money+$repay_manage_impose_money),2);
            }
            else{
                $notice['all_money'] = number_format(($repay_money+$repay_impose_money+$repay_manage_impose_money),2);
            }
            $notice['repay_money'] = number_format($repay_money,2);
            $notice['impose_money'] = number_format($repay_impose_money,2);
            if($get_manage == 0){
                $notice['manage_money'] = number_format($repay_manage_money,2);
            }
            else{
                $notice['manage_money'] = number_format(0,2);
            }
            $notice['mortgage_fee'] = number_format($mortgage_fee,2);
            $notice['manage_impose_money'] = number_format($repay_manage_impose_money,2);

            $GLOBALS['tmpl']->assign("notice",$notice);
            $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
            $msg_data['dest'] = $GLOBALS['user_info']['mobile'];
            $msg_data['send_type'] = 0;
            $msg_data['title'] = "还款短信通知";
            $msg_data['content'] = $msg;
            $msg_data['send_time'] = 0;
            $msg_data['is_send'] = 0;
            $msg_data['create_time'] = TIME_UTC;
            $msg_data['user_id'] = $GLOBALS['user_info']['id'];
            $msg_data['is_html'] = 0;
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
        }

        //还款信息通知
        if(app_conf("WEIXIN_MSG")==1){
            $user_info = get_user_info("*","id = ".$GLOBALS['user_info']['id']);
            if($user_info['wx_openid']!='')
            {
                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM205975633' ");
                $num = $lkey+1;
                if($get_manage ==0){
                    $all_money = number_format(($repay_money+$repay_impose_money+$repay_manage_money+$repay_manage_impose_money),2);
                }
                else{
                    $all_money = number_format(($repay_money+$repay_impose_money+$repay_manage_impose_money),2);
                }
                $weixin_data['first'] = array('value'=>$user_info['user_name'].'您的借款','color'=>'#173177');
                $weixin_data['keyword1']=array('value'=>$deal['sub_name'].'第'.$num.'期','color'=>'#173177');
                $weixin_data['keyword2']=array('value'=>$all_money,'color'=>'#173177');
                weixin_tmpl_send($tmpl['template_id'],$user_info['id'],$weixin_data);
            }
        }

    }

    //判断本借款是否还款完毕
    if($GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." and l_key=".$last_repay_key." AND has_repay <> 1 ") == 0){
        //全部还完
        if($GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." and has_repay = 0 ") == 0){
            //判断获取的信用是否超过限制
            if($GLOBALS['db']->getOne("SELECT sum(point) FROM ".DB_PREFIX."user_point_log WHERE  `type`=6 AND user_id=".$GLOBALS['user_info']['id']) < (int)trim(app_conf('REPAY_SUCCESS_LIMIT'))){
                //获取上一次还款时间
                $befor_repay_time = $GLOBALS['db']->getOne("SELECT MAX(create_time) FROM ".DB_PREFIX."user_point_log WHERE  `type`=6 AND user_id=".$GLOBALS['user_info']['id']);
                $day = ceil((TIME_UTC-$befor_repay_time)/24/3600);
                //当天数大于等于间隔时间 获得信用
                if($day >= (int)trim(app_conf('REPAY_SUCCESS_DAY'))){
                    modify_account(array("point"=>trim(app_conf('REPAY_SUCCESS_POINT'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款",4);
                }
            }

            //用户获得额度
            modify_account(array("quota"=>trim(app_conf('USER_REPAY_QUOTA'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款获得额度",4);

        }
    }


    $GLOBALS['db']->query("UPDATE ".DB_PREFIX."generation_repay_submit SET `memo`='因还款失效',`status`=2 WHERE deal_id=".$deal['id']);

    sys_user_status($GLOBALS['user_info']['id'],false,true);
    syn_deal_status($id);
    syn_transfer_status(0,$id);
    $root["status"] = 1;//0:出错;1:正确;
    $root["show_err"] = "还款完毕，本次还款人数:$repay_user_count";

    return $root;
}

//提前还款操作界面
function getUcInrepayRefund($id){
    $id = intval($id);
    $root = array();
    $root["status"] = 0;//0:出错;1:正确;


    if($id == 0){
        $root["show_err"] = "操作失败！";
        return $root;
    }

    $deal = get_deal($id);
    if(!$deal)
    {
        $root["show_err"] = "借款不存在！";
        return $root;
    }
    if($deal['user_id']!=$GLOBALS['user_info']['id']){
        $root["show_err"] = "不属于你的借款！";
        return $root;
    }
    if($deal['deal_status']!=4){
        $root["show_err"] = "借款不是还款状态！";
        return $root;
    }

    $root["deal"] = $deal;

    $time = TIME_UTC;
    $impose_money = 0;
    //还了几期了
    $has_repay_count =  $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE has_repay = 1 and deal_id=".$id);
    //计算罚息
    $loan_list = get_deal_load_list($deal);

    foreach($loan_list as $k=>$v){
        if($v['has_repay'] == 0)
        {
            $impose_money += floatval($v['impose_money']);
        }
    }

    if($impose_money > 0){
        $root["show_err"] = "请将逾期未还的借款还完才可以进行此操作！";
        return $root;
    }

    $get_manage = $GLOBALS['db']->getOne("SELECT get_manage FROM ".DB_PREFIX."deal_repay WHERE deal_id = ".$deal['id']." and l_key=".$has_repay_count."  ");
    if($get_manage==1){
        $deal['month_manage_money'] = 0;
        $deal['all_manage_money'] = 0;
    }

    $loaninfo['deal'] = $deal;
    $loaninfo['loanlist'] = $loan_list;

    $inrepay_info = inrepay_repay($loaninfo,$has_repay_count);

    $root["true_all_manage_money"] = $inrepay_info["true_manage_money"];
    $root["true_all_manage_money_format"] = format_price($inrepay_info["true_manage_money"]);

    $root["true_all_mortgage_fee"] = $inrepay_info["true_mortgage_fee"];
    $root["true_all_mortgage_fee_format"] = format_price($inrepay_info["true_mortgage_fee"]);

    $root["status"] = 1;//0:出错;1:正确;
    $root["impose_money"] = $inrepay_info['impose_money'];
    $root["impose_money_format"] = format_price($root["impose_money"]);

    $root["total_repay_money"] = $inrepay_info['true_repay_money'];
    $root["total_repay_money_format"] = format_price($root["total_repay_money"]);

    $true_total_repay_money = $inrepay_info['true_repay_money'] + $inrepay_info['impose_money'] + $inrepay_info["true_manage_money"] + $root["true_all_mortgage_fee"];
    $root["true_total_repay_money"] = $true_total_repay_money;
    $root["true_total_repay_money_format"] = format_price($root["true_total_repay_money"]);

    return $root;
}

//提前还款执行程序
function getUCInrepayRepayBorrowMoney($id,$user_id = 0){
    $id = intval($id);

    $root = array();
    $root["status"] = 0;//0:出错;1:正确;

    if($id == 0){
        $root["show_err"] = "操作失败！";
        return $root;
    }

    $deal = get_deal($id);
    if(!$deal)
    {
        $root["show_err"] = "借款不存在！";
        return $root;
    }

    if($user_id > 0){
        $GLOBALS['user_info'] = get_user("*",$user_id);
    }

    if($deal['user_id']!=$GLOBALS['user_info']['id']){
        $root["show_err"] = "不属于你的借款！";
        return $root;
    }
    if($deal['deal_status']!=4){
        $root["show_err"] = "借款不是还款状态！";
        return $root;
    }



    $time = TIME_UTC;
    $impose_money = 0;
    //是否有部分还款的
    $repay_count_ing =  $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE has_repay=2 and deal_id=".$id);
    if($repay_count_ing){
        $root["show_err"] = "请将部分还款的借款还完才可以进行此操作！";
        return $root;
    }

    //计算罚息
    $loan_list = get_deal_load_list($deal);

    $k_repay_key = -1;
    $k_repay_time = 0;
    foreach($loan_list as $k=>$v){
        if($v['has_repay'] == 0)
        {
            if($k_repay_key==-1){
                $k_repay_key = $v['l_key'];
                $k_repay_time = $v['repay_day'];
            }
            $impose_money +=$v['impose_all_money'];
        }
    }

    if($impose_money > 0){
        $root["show_err"] = "请将逾期未还的借款还完才可以进行此操作！";
        return $root;
    }

    if($deal['ips_bill_no']!=""){
        $root["status"] = 2;
        $root["jump"] = APP_ROOT.'/index.php?ctl=collocation&act=RepaymentNewTrade&deal_id='.$deal['id'].'&l_key=all&from='.$GLOBALS['request']['from'];
        $root['jump'] = str_replace("/mapi", "", SITE_DOMAIN.$root['jump']);
        return $root;
    }


    //还了几期了
    $has_repay_count =  $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."deal_repay WHERE has_repay=1 and deal_id=".$id);

    $get_manage = $GLOBALS['db']->getOne("SELECT get_manage FROM ".DB_PREFIX."deal_repay WHERE deal_id = ".$deal['id']." and l_key=".$has_repay_count."  ");
    if($get_manage==1){
        $deal['month_manage_money'] = 0;
        $deal['all_manage_money'] = 0;
    }

    $loaninfo['deal'] = $deal;
    $loaninfo['loanlist'] = $loan_list;

    //返佣
    $rebate_rs = get_rebate_fee($GLOBALS['user_info']['id'],"borrow");
    $loaninfo['deal']['rebate'] = $rebate_rs['rebate'];

    $inrepay_info = inrepay_repay($loaninfo,$has_repay_count);

    $true_repay_money = (float)$inrepay_info['true_repay_money'];
    $true_self_money = (float)$inrepay_info['true_self_money'];
    $impose_money  = (float)$inrepay_info['impose_money'];
    $true_manage_money = (float)$inrepay_info['true_manage_money'];
    $true_mortgage_fee = (float)$inrepay_info['true_mortgage_fee'];
    $true_manage_money_rebate = (float)$inrepay_info['true_manage_money_rebate'];

    $true_total_repay_money = $true_repay_money + $impose_money + $true_manage_money;

    if($true_total_repay_money > $GLOBALS['user_info']['money']){
        $root["show_err"] = "对不起，您的余额不足！";
        return $root;
    }


    //录入到提前还款列表
    $inrepay_data['deal_id'] = $id;
    $inrepay_data['user_id'] = $GLOBALS['user_info']['id'];
    $inrepay_data['repay_money'] = $true_repay_money;
    $inrepay_data['self_money'] = $true_self_money;
    $inrepay_data['impose_money'] = $impose_money;
    $inrepay_data['manage_money'] = $true_manage_money;
    $inrepay_data['mortgage_fee'] = $true_mortgage_fee;
    $inrepay_data['repay_time'] = $k_repay_time;
    $inrepay_data['true_repay_time'] = $time;

    $GLOBALS['db']->autoExecute(DB_PREFIX."deal_inrepay_repay",$inrepay_data,"INSERT");
    $inrepay_id = $GLOBALS['db']->insert_id();
    if($inrepay_id==0){
        $root["show_err"] = "对不起，数据处理失败，请联系客服！";
        return $root;
    }

    //录入还款列表
    $wait_repay_list = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$id." and has_repay=0 ORDER BY l_key ASC");
    $temp_ids = array();
    foreach($wait_repay_list as $k=>$v){
        $repay_data =array();
        $repay_data['has_repay'] = 1;
        $repay_data['true_repay_time'] = $time;
        $repay_data['true_repay_date'] = to_date($time);
        $repay_data['status'] = 0;
        if($k_repay_key==$v['l_key']){
            $repay_data['true_repay_money'] = $true_repay_money;
            $repay_data['impose_money'] = $impose_money;
            $repay_data['true_manage_money'] = $true_manage_money;
            $repay_data['true_mortgage_fee'] = $true_mortgage_fee;
            $repay_data['true_self_money'] = $true_self_money;
            $repay_data['true_interest_money'] = $true_repay_money - $true_self_money;


            $repay_data['true_manage_money_rebate'] = $true_manage_money_rebate;
        }

        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$repay_data,"UPDATE","id=".$v['id']);

        //假如出错 删除掉原来的以插入的数据
        if($GLOBALS['db']->affected_rows() == 0)
        {
            if(count($temp_ids) > 0){
                $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_repay SET has_repay=0 WHERE id in ".implode(",",$temp_ids)."");
                make_repay_plan($deal);
            }
            $root["show_err"] = "对不起，处理数据失败请联系客服！";
            return $root;
        }
        else{
            $temp_ids[] = $v['id'];
        }

    }

    if(count($temp_ids)==0){
        $root["show_err"] = "对不起，处理数据失败请联系客服！";
        return $root;
    }

    //更新用户账户资金记录
    require_once APP_ROOT_PATH.'system/libs/user.php';

    if(round($impose_money,2)!=0)
        modify_account(array("money"=>-round($impose_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款违约金",6);
    if(round($true_manage_money,2)!=0)
        modify_account(array("money"=>-round($true_manage_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款管理费",10);
    if(round($true_mortgage_fee,2)!=0)
        modify_account(array("money"=>-round($true_mortgage_fee,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款抵押物管理费",27);
    if(round($true_repay_money,2)!=0)
        modify_account(array("money"=>-round($true_repay_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款本息",6);

    //用户获得额度
    if(intval(app_conf('USER_REPAY_QUOTA'))!=0)
        modify_account(array("quota"=>trim(app_conf('USER_REPAY_QUOTA'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款获得额度",6);

    /*
    modify_account(array("money"=>-round($impose_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款违约金",6);
    modify_account(array("money"=>-round($true_manage_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款管理费",10);
    modify_account(array("money"=>-round($true_mortgage_fee,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款抵押物管理费",27);
    modify_account(array("money"=>-round($true_repay_money,2)),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款本息",6);
    //用户获得额度
    modify_account(array("quota"=>trim(app_conf('USER_REPAY_QUOTA'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款获得额度",6);
    */

    //借款者返佣金
    if($true_manage_money_rebate!=0){
        /*ok*/
        $reback_memo = '借款“<a href="'.$deal["url"].'">'.$deal["name"].'</a>”，借款者'.$deal["user"]["user_name"];
        reback_rebate_money($GLOBALS['user_info']['id'],$true_manage_money_rebate,"borrow",$reback_memo);
    }


    //判断获取的信用是否超过限制
    if($GLOBALS['db']->getOne("SELECT sum(point) FROM ".DB_PREFIX."user_point_log WHERE `type`=6 AND user_id=".$GLOBALS['user_info']['id']) < (int)trim(app_conf('REPAY_SUCCESS_LIMIT'))){
        //获取上一次还款时间
        $befor_repay_time = $GLOBALS['db']->getOne("SELECT MAX(create_time) FROM ".DB_PREFIX."user_point_log WHERE `type`=6 AND user_id=".$GLOBALS['user_info']['id']);
        $day = ceil(($time-$befor_repay_time)/24/3600);
        //当天数大于等于间隔时间 获得信用
        if($day >= (int)trim(app_conf('REPAY_SUCCESS_DAY'))){
            modify_account(array("point"=>trim(app_conf('REPAY_SUCCESS_POINT'))),$GLOBALS['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款",6);
        }
    }



    //用户回款
    /**
     * 获取某一期的用户还款列表
     * array $deal_info 借款信息
     * int $user_id 用户ID 为0代表全部
     * int $lkey  第几期 -1 全部
     * int $ukey 第几个投标人 -1 全部
     * int $true_time  真实还款时间
     * int $get_type  0 全部 1代表未还的  2 代表已还的
     * int $r_type = 0; 返回类型; 1:只返回一个数组; $result['item']
     * string $limit; 查询限制数量; 0,20  $result['count']
     */
    $user_loan_list = get_deal_user_load_list($deal,0,-1,-1,$time,1,0,'');
    $learn_id = 0;
    $load_id = 0;

    foreach($user_loan_list as $lllk=>$lllv){//循环用户
        //本金
        $user_self_money = 0;
        //本息
        $user_repay_money = 0;
        //违约金
        $user_impose_money = 0;
        //管理费
        $user_manage_money = 0;
        //利息管理费
        $user_manage_interest_money =0;
        //返佣金
        $manage_interest_money_rebate = 0;

        //奖励
        $user_reward_money = 0;

        foreach($lllv as $kk=>$vv){//循环期数

            $in_user_id = $vv['user_id'];
            //判断是否转让了债权
            if((int)$vv['t_user_id'] == 0){
                $loan_user_info['user_name'] = $vv['user_name'];
                $loan_user_info['email'] = $vv['email'];
                $loan_user_info['mobile'] = $vv['mobile'];
            }
            else{
                $in_user_id = $vv['t_user_id'];
                $loan_user_info['user_name'] = $vv['t_user_name'];
                $loan_user_info['email'] = $vv['t_email'];
                $loan_user_info['mobile'] = $vv['t_mobile'];
            }

            $user_load_data = array();
            $user_load_data['true_repay_time'] = $time;
            $user_load_data['true_repay_date'] = to_date($time);
            $user_load_data['is_site_repay'] = 0;
            $user_load_data['status'] = 0;

            if($k_repay_key==$vv['l_key']){
                $loadinfo = array();
                $loadinfo['deal']['rate'] = $deal['rate'];
                $loadinfo['deal']['loantype'] = $deal['loantype'];
                $loadinfo['deal']['repay_time'] = $deal['repay_time'];
                $loadinfo['deal']['borrow_amount'] = $vv['money'];
                $loadinfo['deal']['repay_start_time'] = $deal['repay_start_time'];
                $loadinfo['deal']['month_manage_money'] = $vv['manage_money'];
                $loadinfo['deal']['mortgage_fee'] = $vv['mortgage_fee'];
                $loadinfo['deal']['manage_interest_money'] = $vv['manage_interest_money'];
                $deal =  get_user_load_fee($in_user_id,0,$deal);
                $loadinfo['deal']['user_loan_interest_manage_fee'] = $deal['user_loan_interest_manage_fee'];
                $rebate_rs = get_rebate_fee($in_user_id,"invest");
                $loadinfo['deal']['rebate'] = $rebate_rs['rebate'];

                $loadinfo['deal']['manage_interest_money_rebate'] = $vv['manage_interest_money_rebate'];
                $loadinfo['deal']['month_repay_money'] = $vv['month_repay_money'];
                $loadinfo['deal']['compensate_fee'] = $deal['compensate_fee'];
                if($deal['repay_time_type'] == 1)
                    $loadinfo['deal']['all_manage_money'] = $vv['manage_money'];
                else
                    $loadinfo['deal']['all_manage_money'] = $vv['manage_money'] * $deal['repay_time'];

                $loadinfo['deal']['repay_time_type'] = $deal['repay_time_type'];

                $user_load_rs = inrepay_repay($loadinfo,$has_repay_count);

                $user_load_data['true_repay_money'] = $user_load_rs['true_repay_money'];
                $user_load_data['true_self_money'] = $user_load_rs['true_self_money'];
                $user_load_data['impose_money'] = $user_load_rs['impose_money'];
                $user_load_data['true_interest_money'] = $user_load_rs['true_repay_money'] - $user_load_rs['true_self_money'];
                $user_load_data['true_manage_money'] = $user_load_rs['true_manage_money'];
                $user_load_data['true_mortgage_fee'] = $user_load_rs['true_mortgage_fee'];
                $user_load_data['true_manage_interest_money'] = $user_load_rs['true_manage_interest_money'];
                $user_load_data['true_manage_interest_money_rebate'] = $user_load_rs['true_manage_interest_money_rebate'];
                $user_load_data['true_repay_manage_money'] = $true_manage_money / count($user_loan_list);
                $user_load_data['true_reward_money'] = 0;
                if((int)$vv['is_winning']==1 && (int)$vv['income_type']==2 && (float)$vv['income_value']!=0){
                    $user_load_data['true_reward_money'] = $user_load_data['true_interest_money'] * (float)$vv['income_value']*0.01;
                }

                $user_self_money = $user_load_data['true_self_money'];
                $user_repay_money = $user_load_data['true_repay_money'];
                $user_impose_money = $user_load_data['impose_money'];
                $user_manage_money = $user_load_data['true_manage_money'];
                $user_manage_interest_money = $user_load_data['true_manage_interest_money'];
                $manage_interest_money_rebate = $user_load_data['true_manage_interest_money_rebate'];
                $user_reward_money = $user_load_data['true_reward_money'];

            }

            $user_load_data['has_repay'] = 1;
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$user_load_data,"UPDATE","id=".$vv['id']);

            $learn_id = $vv['learn_id'];
            $load_id = $vv['load_id'];

            //普通会员邀请返利
            get_referrals($vv['id']);
        }

        if($user_repay_money >0 || $user_impose_money >0 || $user_manage_money > 0 || $user_manage_interest_money >0 || $user_reward_money > 0){
            $all_repay_money = number_format($GLOBALS['db']->getOne("SELECT (sum(repay_money)-sum(self_money) + sum(impose_money)) as shouyi FROM ".DB_PREFIX."deal_load_repay WHERE  has_repay = 1 and deal_id=".$v['deal_id']." AND user_id=".$v['user_id']),2);
            $all_impose_money = number_format($GLOBALS['db']->getOne("SELECT sum(impose_money) FROM ".DB_PREFIX."deal_load_repay WHERE has_repay = 1 and deal_id=".$v['deal_id']." AND user_id=".$v['user_id']),2);

            //$content = "您好，您在".app_conf("SHOP_TITLE")."的投标 “<a href=\"".$deal['url']."\">".$deal['name']."</a>”提前还款,";
            //$content .= "本次投标共获得收益:".$all_repay_money."元,其中违约金为:".$all_impose_money."元,本次投标已回款完毕！";

            //更新用户账户资金记录
            modify_account(array("money"=>$user_repay_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],回报本息",5);

            modify_account(array("money"=>$user_impose_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前回收违约金",7);

            if($user_manage_money>0)
                modify_account(array("money"=>-$user_manage_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],投标管理费",20);

            if($user_reward_money>0)
                modify_account(array("money"=>-$user_reward_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],投标奖励",28);

            if($user_manage_interest_money!=0)
                modify_account(array("money"=>-$user_manage_interest_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],投标利息管理费",20);

            //扣除体验金
            if($learn_id > 0){
                $load_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_load where id=".$load_id);
                if($load_info){
                    //还需回收多少
                    $back_learn_money = 0;
                    if(floatval($load_info['learn_money']) > floatval($load_info['back_learn_money'])){
                        $back_learn_money = floatval($load_info['learn_money']) - floatval($load_info['back_learn_money']);
                    }
                    if($back_learn_money > 0){
                        if(($user_repay_money + $user_impose_money -$user_manage_money - $user_reward_money -$user_manage_interest_money) >= $back_learn_money){
                            modify_account(array("money"=>-$back_learn_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],体验金回收",54);
                        }
                        else{
                            $back_learn_money = $user_repay_money + $user_impose_money -$user_manage_money - $user_reward_money -$user_manage_interest_money;
                            modify_account(array("money"=>-$back_learn_money),$in_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],体验金回收",54);
                        }
                        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load SET  back_learn_money = back_learn_money + ".$back_learn_money." where id=".$load_id);
                    }
                }
            }

            //投资者返佣金
            if(floatval($manage_interest_money_rebate)!=0){
                /*ok*/
                $reback_memo = "借款“<a href'".$deal['url']."'>".$deal["name"]."</a>”,投资者".$loan_user_info["user_name"]."，第".(intval($k_repay_key)+1)."期,提前还款";
                reback_rebate_money($in_user_id,$manage_interest_money_rebate,"invest",$reback_memo);
            }

            $msg_conf = get_user_msg_conf($in_user_id);
            //短信通知
            if(app_conf("SMS_ON")==1&&app_conf('SMS_REPAY_TOUSER_ON')==1){

                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_SMS'",false);
                $tmpl_content = $tmpl['content'];

                $notice['user_name'] = $loan_user_info['user_name'];
                $notice['deal_name'] = $deal['sub_name'];
                $notice['deal_url'] = $deal['url'];
                $notice['site_name'] = app_conf("SHOP_TITLE");

                $notice['repay_money'] = round($user_repay_money+$user_impose_money,2);

                //$notice['repay_money'] = $vv['month_repay_money']+$vv['impose_money'];

                $notice['all_repay_money'] = $all_repay_money;
                $notice['impose_money'] = $all_impose_money;

                $GLOBALS['tmpl']->assign("notice",$notice);
                $sms_content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);

                $msg_data['dest'] = $loan_user_info['mobile'];
                $msg_data['send_type'] = 0;
                $msg_data['title'] = $msg_data['content'] = addslashes($sms_content);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = $time;
                $msg_data['user_id'] = $in_user_id;
                $msg_data['is_html'] = 0;
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }

            //回款通知
            if(app_conf("WEIXIN_MSG")==1){
                $user_info = get_user_info("*","id = ".$in_user_id);
                if($user_info['wx_openid']!='')
                {
                    $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM207940989' ");
                    $repay_money = number_format(($vv['month_repay_money']+$vv['impose_money']),2);
                    $weixin_data['first'] = array('value'=>'投标回款短信通知','color'=>'#173177');
                    $weixin_data['keyword1']=array('value'=>$deal['sub_name'],'color'=>'#173177');
                    $weixin_data['keyword2']=array('value'=>$loan_user_info['user_name'],'color'=>'#173177');
                    $weixin_data['keyword3']=array('value'=>$repay_money,'color'=>'#173177');
                    weixin_tmpl_send($tmpl['template_id'],$in_user_id,$weixin_data);
                }
            }
            //站内信

            $notices['shop_title'] = app_conf("SHOP_TITLE");
            $notices['url'] = "“<a href=\"".$deal['url']."\">".$deal['name']."</a>”";
            $notices['repay_money'] = $all_repay_money;
            $notices['impose_money'] = $all_impose_money;

            $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_REPAY_MONEY_TQTB'",false);
            $GLOBALS['tmpl']->assign("notice",$notices);
            $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);

            if($msg_conf['sms_bidrepaid']==1)
                send_user_msg("",$content,0,$in_user_id,$time,0,true,9);
            //邮件
            if($msg_conf['mail_bidrepaid']==1 && app_conf('MAIL_ON')==1){

                $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_EMAIL'",false);
                $tmpl_content = $tmpl['content'];

                $notice['user_name'] = $loan_user_info['user_name'];
                $notice['deal_name'] = $deal['sub_name'];
                $notice['deal_url'] = $deal['url'];
                $notice['site_name'] = app_conf("SHOP_TITLE");
                $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
                $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
                $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
                $notice['repay_money'] = round($user_repay_money+$user_impose_money,2);

                //$notice['repay_money'] = $vv['month_repay_money']+$vv['impose_money'];

                $notice['all_repay_money'] = $all_repay_money;
                $notice['impose_money'] = $all_impose_money;

                $GLOBALS['tmpl']->assign("notice",$notice);

                $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
                $msg_data['dest'] = $loan_user_info['email'];
                $msg_data['send_type'] = 1;
                $msg_data['title'] = "“".$deal['name']."”回款通知";
                $msg_data['content'] = addslashes($msg);
                $msg_data['send_time'] = 0;
                $msg_data['is_send'] = 0;
                $msg_data['create_time'] = $time;
                $msg_data['user_id'] = $in_user_id;
                $msg_data['is_html'] = $tmpl['is_html'];
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
            }
        }

    }

    /*
    $content = "您好，您在".app_conf("SHOP_TITLE")."的借款 “<a href=\"".$deal['url']."\">".$deal['name']."</a>”成功提前还款".number_format($true_total_repay_money,2)."元，";
    $content .= "其中违约金为:".number_format($impose_money,2)."元,本笔借款已还款完毕！";
    */
    $notices['shop_title'] = app_conf("SHOP_TITLE");
    $notices['url'] = "“<a href=\"".$deal['url']."\">".$deal['name']."</a>”";
    $notices['repay_money'] = number_format($true_total_repay_money,2);
    $notices['impose_money'] = number_format($impose_money,2);
    $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_REPAY_MONEY_TQJK'",false);
    $GLOBALS['tmpl']->assign("notice",$notices);
    $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);
    //站内信
    send_user_msg("",$content,0,$GLOBALS['user_info']['id'],$time,0,true,8);

    //短信通知
    if(app_conf("SMS_ON")==1&&app_conf('SMS_SEND_REPAY')==1){
        //$sms_content = "尊敬的".app_conf("SHOP_TITLE")."用户".$GLOBALS['user_info']['user_name']."，您成功提前还款".number_format($true_total_repay_money,2)."元，其中违约金为:".number_format($impose_money,2)."元,感谢您的关注和支持。【".app_conf("SHOP_TITLE")."】";
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_REPAY_SUCCESS_MSG'",false);
        $tmpl_content = $tmpl['content'];
        $notice['user_name'] = $GLOBALS['user_info']['user_name'];
        $notice['deal_name'] = $deal['sub_name'];
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['index'] = $has_repay_count+1;
        $notice['status'] = "成功提前";
        $notice['all_money'] = number_format($true_total_repay_money,2);
        $notice['repay_money'] = number_format($true_repay_money,2);
        $notice['impose_money'] = number_format($impose_money,2);
        $notice['manage_money'] = number_format($true_manage_money,2);
        $notice['manage_impose_money'] = 0;

        $GLOBALS['tmpl']->assign("notice",$notice);
        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);

        $msg_data['dest'] = $GLOBALS['user_info']['mobile'];
        $msg_data['send_type'] = 0;
        $msg_data['title'] = "提前还款短信通知";
        $msg_data['content'] = $msg;
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = $time;
        $msg_data['user_id'] = $GLOBALS['user_info']['id'];
        $msg_data['is_html'] = 0;
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }

    $GLOBALS['db']->query("UPDATE ".DB_PREFIX."generation_repay_submit SET `memo`='因还款失效',`status`=2 WHERE deal_id=".$deal['id']);


    //VIP升级 -提前还款
    $type = 1;
    $type_info = 4;
    $resultdate = syn_user_vip($GLOBALS['user_info']['id'],$type,$type_info);

    syn_deal_status($id);
    sys_user_status($GLOBALS['user_info']['id'],false,true);
    syn_transfer_status(0,$id);
    $root["status"] = 1;//0:出错;1:正确;
    $root["show_err"] = "操作成功!";
    return $root;
}


/**
 * 获取积分商品
 */
function get_goods($id=0,$is_effect=1)
{
    $goods = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."goods where id = ".intval($id));
    return $goods;
}

/**
 * 获取积分商城商品列表
 */
function get_goods_list($limit="", $where='',$orderby = '')
{
    $count_sql = "select count(*) from ".DB_PREFIX."goods where 1=1  ";
    $sql = "select * from ".DB_PREFIX."goods where 1=1 ";

    if($where != '')
    {
        $sql.=" and ".$where;
        $count_sql.=" and ".$where;
    }

    if($orderby=='')
        $sql.=" order by sort desc ";
    else
        $sql.=" order by ".$orderby;

    if($limit!=""){
        $sql .=" limit ".$limit;
    }

    $goods_count = $GLOBALS['db']->getOne($count_sql);
    if($goods_count > 0){
        $goods = $GLOBALS['db']->getAll($sql);

    }
    else{
        $deals = array();
    }
    return array('list'=>$goods,'count'=>$goods_count);
}

//债权转让常规检测;
function check_trans($id,$paypassword){
    $paypassword = strim($paypassword);
    $id = intval($id);

    $root = array();
    $root["status"] = 0;//0:出错;1:正确;

    if(!$GLOBALS['user_info']){
        $root["show_err"] = $GLOBALS['lang']['PLEASE_LOGIN_FIRST'];
        return $root;
    }


    if($paypassword==""){
        $root["show_err"] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
        return $root;
    }

    if(md5($paypassword)!=$GLOBALS['user_info']['paypassword']){
        $root["show_err"] = $GLOBALS['lang']['PAYPASSWORD_ERROR'];//.$GLOBALS['user_info']['paypassword'].';'.md5($paypassword).';'.$paypassword;
        return $root;
    }



    $deal_id = $GLOBALS['db']->getOne("SELECT deal_id FROM ".DB_PREFIX."deal_load_transfer WHERE id=".$id);
    if($deal_id==0){
        $root["show_err"] = "不存在的债权";
        return $root;
    }
    else{
        syn_deal_status($deal_id);
    }

    $condition = ' AND dlt.id='.$id.' AND d.deal_status = 4 and d.is_effect=1 and d.is_delete=0 and d.repay_time_type =1 and  d.publish_wait=0 ';
    $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id ";

    $sql = 'SELECT dlt.load_id,dlt.id,dlt.t_user_id,dlt.transfer_amount,dlt.user_id,dlt.near_repay_time,d.next_repay_time,d.last_repay_time,d.rate,d.repay_start_time,d.repay_time,dlt.load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time,d.user_id as duser_id,d.ips_bill_no FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $transfer = $GLOBALS['db']->getRow($sql);

    if($transfer){
        if($transfer['user_id']==$GLOBALS['user_info']['id']){
            $root["show_err"] = "不能购买自己转让的债权";
            return $root;
        }

        if($transfer['duser_id']==$GLOBALS['user_info']['id']){
            $root["show_err"] = "不能购买自己的的借贷债权";
            return $root;
        }

        if($transfer['tras_status']==0){
            $root["show_err"] = "债权已撤销";
            return $root;
        }

        if(intval($transfer['t_user_id'])>0){
            $root["show_err"] = "债权已转让";
            return $root;
        }

        //下个还款日
        if(intval($transfer['next_repay_time']) == 0){
            $transfer['next_repay_time'] = next_replay_month($transfer['repay_start_time']);
        }

        if($transfer['next_repay_time'] - TIME_UTC  + 24*3600 - 1 <= 0){
            $root["show_err"] = "债权转让已过期";
            return $root;
        }

        $root["transfer"] = $transfer;
        $root["deal_id"] = $deal_id;
    }
    else{
        $root["show_err"] = "债权转让不存在";
        return $root;
    }
    if($transfer['ips_bill_no']!="")
        $root["status"] = 2;
    else
        $root["status"] = 1;//0:出错;1:正确;
    return $root;
}

//债权转让;
function dotrans($id,$paypassword){
    $paypassword = strim($paypassword);
    $id = intval($id);

    $root = array();
    $root["status"] = 0;//0:出错;1:正确;

    $result = check_trans($id,$paypassword);

    if ($result['status'] == 0){
        $root["show_err"] = $result["show_err"];
        return $root;
    }

    if ($result['status'] == 2){
        $root["status"] = 2;
        $root["jump"] = "http://wap.yzlicai.com/index.php?m=home&c=collocation&a=RegisterCretansfer&id=$id&t_user_id=".$GLOBALS['user_info']['id']."&paypassword=".$paypassword."&from=".$GLOBALS['request']['from'];
        $root['jump'] = str_replace(array("/mapi","/wap"), "", SITE_DOMAIN.$root['jump']);
        return $root;
    }

    $transfer = $result["transfer"];
    $deal_id = $result["deal_id"];


    if($transfer){
        if(floatval($transfer['transfer_amount']) > floatval($GLOBALS['user_info']['money'])){
            $root["show_err"] = "账户余额不足";
            return $root;
        }

        $transfer_date = to_date(TIME_UTC);
        $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load_transfer set t_user_id = ".$GLOBALS['user_info']['id'].",transfer_time='".TIME_UTC."',transfer_date='".$transfer_date."' WHERE id=".$id." and t_user_id =0 AND status=1 AND near_repay_time- ".next_replay_month(to_timespan(to_date(TIME_UTC,"Y-m-d"),"Y-m-d"),-1)." + 24*3600 - 1 > 0 ");
        if($GLOBALS['db']->affected_rows()){
            $deal =  get_user_load_fee($GLOBALS['user_info']['id'],$deal_id);
            $manage_money = $transfer['load_money'] * floatval($deal["user_loan_manage_fee"]) * 0.01;
            //更新相应的回款计划
            $GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load_repay SET t_user_id='".$GLOBALS['user_info']['id']."',manage_money='".$manage_money."',manage_interrest_money = interrest_money*".(floatval($deal["user_loan_interest_manage_fee"])*0.01)." WHERE  user_id=".$transfer['user_id']." and load_id=".$transfer['load_id']." and repay_time > ".$transfer['near_repay_time'] );

            require APP_ROOT_PATH."/system/libs/user.php";
            //承接人扣除转让费
            modify_account(array("money"=>-floatval($transfer['transfer_amount'])),$GLOBALS['user_info']['id'],"债:Z-".$transfer['load_id'].",承接金",16);
            //转让人接受转让费
            modify_account(array("money"=>floatval($transfer['transfer_amount'])),$transfer['user_id'],"债:Z-".$transfer['load_id'].",转让金",15);

            $user_load_transfer_fee = $GLOBALS['db']->getOne("SELECT user_load_transfer_fee FROM ".DB_PREFIX."deal WHERE id=".$deal_id);
            //扣除转让人的手续费
            if(trim($user_load_transfer_fee)!=""){
                $transfer_fee = $transfer['transfer_amount']*floatval(trim($user_load_transfer_fee));
                if($transfer_fee!=0){
                    $transfer_fee = $transfer_fee / 100;
                }
                modify_account(array("money"=>-floatval($transfer_fee)),$transfer['user_id'],"债:Z-".$transfer['load_id'].",转让管理费",17);
            }


            dotrans_ok($id);


            $root["status"] = 1;//0:出错;1:正确;
            $root["show_err"] = "转让成功";
            return $root;
        }
        else{
            $root["show_err"] = "转让失败";
            return $root;
        }
    }
    else{
        $root["show_err"] = "债权转让不存在";
        return $root;
    }

}

function dotrans_ok($transfer_id){

    $transfer = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_load_transfer where id = ".$transfer_id);
    //发送消息
    $msg_conf = get_user_msg_conf($transfer['user_id']);
    //if($msg_conf['sms_transfer']==1 || $msg_conf['mail_transfer']==1){
    $transfer['tuser'] = get_user("*",$transfer['t_user_id']);
    $transfer['user'] = get_user("*",$transfer['user_id']);
    //}

    if($msg_conf['sms_transfer']==1){
        //您好，您在{$notice.shop_title}的债权{$notice.url}成功转让给：{$notice.url_name}
        //$content = "您好，您在".app_conf("SHOP_TITLE")."的债权 “<a href=\"".url("index","transfer#detail",array("id"=>$transfer['id']))."\">Z-".$transfer['load_id']."</a>” 成功转让给：<a href=\"".$transfer['tuser']['url']."\">".$transfer['tuser']['user_name']."</a>";

        $notices['shop_title']=app_conf("SHOP_TITLE");
        $notices['url']="“<a href=\"".url("index","transfer#detail",array("id"=>$transfer['id']))."\">Z-".$transfer['load_id']."</a>”";
        $notices['url_name']=	"<a href=\"".$transfer['tuser']['url']."\">".$transfer['tuser']['user_name']."</a>";

        $tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_TRANSFER_REVOKE_USER'",false);
        $GLOBALS['tmpl']->assign("notice",$notices);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);
        send_user_msg("",$content,0,$transfer['user_id'],TIME_UTC,0,true,18);
    }
    //邮件
    if($msg_conf['mail_transfer']==1 && app_conf('MAIL_ON')==1){
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_MAIL_TRANSFER_SUCCESS'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $transfer['user']['user_name'];
        $notice['transfer_time'] = to_date($transfer['create_time'],"Y年m月d日");
        $notice['transfer_id'] = "Z-".$transfer['load_id'];
        $notice['deal_url'] = SITE_DOMAIN.url("index","transfer#detail",array("id"=>$transfer['id']));
        $notice['site_name'] = app_conf("SHOP_TITLE");
        $notice['site_url'] = SITE_DOMAIN.APP_ROOT;
        $notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
        $notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");



        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $transfer['user']['email'];
        $msg_data['send_type'] = 1;
        $msg_data['title'] = "“债权：Z-".$transfer['load_id']."”转让通知";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $transfer['user_id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }

    if(app_conf('SMS_ON')==1){
        $tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_SMS_TRANSFER_SUCCESS'",false);
        $tmpl_content = $tmpl['content'];

        $notice['user_name'] = $transfer['user']['user_name'];
        $notice['transfer_time'] = to_date($transfer['create_time'],"Y年m月d日");
        $notice['transfer_id'] = "Z-".$transfer['load_id'];
        $notice['site_name'] = app_conf("SHOP_TITLE");


        $GLOBALS['tmpl']->assign("notice",$notice);

        $msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
        $msg_data['dest'] = $transfer['user']['mobile'];
        $msg_data['send_type'] = 0;
        $msg_data['title'] = "“债权：Z-".$transfer['load_id']."”转让通知";
        $msg_data['content'] = addslashes($msg);
        $msg_data['send_time'] = 0;
        $msg_data['is_send'] = 0;
        $msg_data['create_time'] = TIME_UTC;
        $msg_data['user_id'] = $transfer['user_id'];
        $msg_data['is_html'] = $tmpl['is_html'];
        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
    }

    //发送债权协议
    send_transfer_contract_email($transfer_id);
}


/**
 * 更新 用户回款 计划数据
 * @param unknown_type $deal_id
 * @param unknown_type $deal_repay_id
 */
function syn_deal_repay_status($deal_id,$deal_repay_id){
    //has_repay 0未收到还款，1已收到还款
    $deal_id = intval($deal_id);
    $deal_repay_id = intval($deal_repay_id);

    $deal = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal WHERE id=".$deal_id);
    $deal['url'] = url("index","deal",array("id"=>$deal['id']));
    $deal["user"] = $GLOBALS['db']->getRow("SELECT *,AES_DECRYPT(real_name_encrypt,'".AES_DECRYPT_KEY."') as real_name,AES_DECRYPT(email_encrypt,'".AES_DECRYPT_KEY."') as email,AES_DECRYPT(idno_encrypt,'".AES_DECRYPT_KEY."') as idno,AES_DECRYPT(money_encrypt,'".AES_DECRYPT_KEY."') as money,AES_DECRYPT(mobile_encrypt,'".AES_DECRYPT_KEY."') as mobile FROM ".DB_PREFIX."user WHERE id=".$deal['user_id']);

    //未还款记录数
    $sql = "select count(*) from ".DB_PREFIX."deal_load_repay where has_repay = 0 and deal_id = ".$deal_id . " and repay_id = ".$deal_repay_id;
    $has_repay_0 = $GLOBALS['db']->getOne($sql);

    //已经还款记录数
    $sql = "select count(*) from ".DB_PREFIX."deal_load_repay where has_repay = 1 and deal_id = ".$deal_id . " and repay_id = ".$deal_repay_id;
    $has_repay_1 = $GLOBALS['db']->getOne($sql);

    //第几期
    $kk = $GLOBALS['db']->getOne("select l_key from ".DB_PREFIX."deal_load_repay where deal_id = ".$deal_id . " and repay_id = ".$deal_repay_id);



    //has_repay 0未还,1已还 2部分还款
    if (($has_repay_0 == 0 && $has_repay_1 == 0) || ($has_repay_0 == 0 && $has_repay_1 > 0)){

        $deal_rs_sql = "select sum(true_interest_money) as total_true_interest_money," .
            "sum(true_self_money) as total_true_self_money," .
            "sum(true_repay_money) as total_true_repay_money," .
            "sum(true_repay_manage_money) as total_true_repay_manage_money," .
            "sum(repay_manage_impose_money) as total_repay_manage_impose_money, " .
            "sum(true_mortgage_fee) as total_true_mortgage_fee, " .
            "sum(impose_money) as total_impose_money ".
            "from ".DB_PREFIX."deal_load_repay where deal_id = ".$deal_id . " and repay_id = ".$deal_repay_id;

        $deal_rs = $GLOBALS['db']->getRow($deal_rs_sql);
        $last_Rs = $GLOBALS['db']->getRow("SELECT `status`,`true_repay_time`,`repay_time` from ".DB_PREFIX."deal_load_repay where deal_id = ".$deal_id . " and repay_id = ".$deal_repay_id." ORDER BY `true_repay_time` DESC");

        $deal_repay_data['true_repay_money'] =  $deal_rs['total_true_repay_money'];
        $deal_repay_data['true_manage_money'] =  $deal_rs['total_true_repay_manage_money'];
        $deal_repay_data['true_mortgage_fee'] =  $deal_rs['total_true_mortgage_fee'];
        $deal_repay_data['manage_impose_money'] =  $deal_rs['total_repay_manage_impose_money'];
        $deal_repay_data['true_self_repay'] =  $deal_rs['total_true_self_money'];
        $deal_repay_data['impose_money'] =  $deal_rs['total_impose_money'];
        $deal_repay_data['true_interest_money'] =  $deal_rs['total_true_interest_money'];
        $deal_repay_data['true_repay_time'] = $last_Rs['true_repay_time'];
        $deal_repay_data['true_repay_date'] = to_date($last_Rs['true_repay_time']);
        $deal_repay_data['status'] =  $last_Rs['status'];
        $deal_repay_data['has_repay'] =  1;

        //返佣金额
        $rebate_rs = get_rebate_fee($deal['user_id'],"borrow");
        $deal_repay_data['true_manage_money_rebate'] =floatval($deal_repay_data['true_manage_money']) * floatval($rebate_rs['rebate'])/100;

        $true_manage_money_rebate = $deal_repay_data['true_manage_money']* floatval($rebate_rs['rebate'])/100;
        //借款者返佣
        if($true_manage_money_rebate!=0){
            /*ok*/
            $reback_memo = sprintf($GLOBALS['lang']["BORROW_REBATE_LOG"],$deal["url"],$deal["name"],$deal["user"]["user_name"],intval($kk)+1);
            reback_rebate_money($deal['user_id'],$true_manage_money_rebate,"borrow",$reback_memo);
        }

        require_once APP_ROOT_PATH."system/libs/user.php";

        if($last_Rs['status'] > 1){
            $impose_day = ceil(($last_Rs['true_repay_time'] - $last_Rs['repay_time'] + 24*3600 - 1)/24/3600);
            //VIP降级-逾期还款
            $type = 2;
            $type_info = 5;
            $resultdate = syn_user_vip($deal['user_id'],$type,$type_info);

            if($impose_day < app_conf('YZ_IMPSE_DAY')){
                modify_account(array("point"=>trim(app_conf('IMPOSE_POINT'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,逾期还款",11);
                $repay_update_data['status'] = 2;
            }
            else{
                modify_account(array("point"=>trim(app_conf('YZ_IMPOSE_POINT'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],第".($kk+1)."期,严重逾期",11);
                $repay_update_data['status'] = 3;
            }
        }
        elseif($last_Rs['status']==1){
            //VIP升级 -正常还款
            $type = 1;
            $type_info = 3;
            $resultdate = syn_user_vip($deal['user_id'],$type,$type_info);
        }
        elseif($last_Rs['status']==0){
            //VIP升级 -提前还款
            $type = 1;
            $type_info = 4;
            $resultdate = syn_user_vip($deal['user_id'],$type,$type_info);
        }

        $GLOBALS['db']->autoExecute(DB_PREFIX."deal_repay",$deal_repay_data,"UPDATE","id = ".$deal_repay_id);
        $last_repay_key =$kk;
        //判断本借款是否还款完毕
        if($GLOBALS['db']->getOne("SELECT count(*)  FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." and l_key=".$last_repay_key." AND has_repay <> 1 ") == 0){
            //全部还完
            if($GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."deal_repay WHERE deal_id=".$deal['id']." and has_repay=0 ") == 0){

                //判断获取的信用是否超过限制
                if($GLOBALS['db']->getOne("SELECT sum(point) FROM ".DB_PREFIX."user_point_log WHERE  `type`=6 AND user_id=".$deal['user_id']) < (int)trim(app_conf('REPAY_SUCCESS_LIMIT'))){
                    //获取上一次还款时间
                    $befor_repay_time = $GLOBALS['db']->getOne("SELECT MAX(create_time) FROM ".DB_PREFIX."user_point_log WHERE  `type`=6 AND user_id=".$deal['user_id']);
                    $day = ceil(($last_Rs['true_repay_time']-$befor_repay_time)/24/3600);
                    //当天数大于等于间隔时间 获得信用
                    if($day >= (int)trim(app_conf('REPAY_SUCCESS_DAY'))){
                        modify_account(array("point"=>trim(app_conf('REPAY_SUCCESS_POINT'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款",4);
                    }
                }

                //用户获得额度
                modify_account(array("quota"=>trim(app_conf('USER_REPAY_QUOTA'))),$deal['user_id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款获得额度",4);

            }
        }

        sys_user_status(intval($GLOBALS['user_info']['id']),false,true);
        syn_deal_status($deal_id);
        syn_transfer_status(0,$deal_id);

    }else if ($has_repay_0 > 0 && $has_repay_1 == 0){
        $sql = "update ".DB_PREFIX."deal_repay set has_repay = 0 where id = ".$deal_repay_id;
    }else{
        $sql = "update ".DB_PREFIX."deal_repay set has_repay = 2 where id = ".$deal_repay_id;
    }
    $GLOBALS['db']->query($sql);
}

/**
 * 算出投资收益
 */
function bid_calculate($data){
    $uloantype =  intval($data['uloantype']);

    if($uloantype==1){
        $data['money'] = intval($data['money']) * floatval($data['minmoney']);
    }

    $deal['borrow_amount'] = floatval($data['money']);
    $deal['rate'] = floatval($data['rate']);
    $deal['repay_time'] = floatval($data['repay_time']);
    $deal['repay_time_type'] = intval($data['repay_time_type']);
    $deal['loantype'] = intval($data['loantype']);


    if($deal['repay_time_type']==0){
        $all_manage_money = $deal['borrow_amount'] * floatval($data['user_loan_manage_fee']) * 0.01 / 30;
    }
    else{
        $all_manage_money = $deal['borrow_amount'] * floatval($data['user_loan_manage_fee']) * 0.01 * $deal['repay_time'];
    }

    $deal_rs = deal_repay_money($deal);
    $deal_fee['user_loan_interest_manage_fee'] = floatval($data['user_loan_interest_manage_fee']);
    if($GLOBALS['user_info']){
        $deal_fee = get_user_load_fee($GLOBALS['user_info']['id'],0,$deal_fee);
    }
    $all_manage_money += ($deal_rs['remain_repay_money'] - floatval($data['money'])) * floatval($deal_fee['user_loan_interest_manage_fee']) * 0.01;

    return number_format($deal_rs['remain_repay_money'] - floatval($data['money']) - floatval($all_manage_money),2);
}


function get_collect_list($limit,$user_id)
{
    $user_id = intval($user_id);
    $sql_count = "select count(*) from ".DB_PREFIX."deal_collect where user_id = ".$user_id;
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0){
        $sql = "select d.*,c.create_time as add_time ,c.id as cid,u.user_name,u.level_id,u.province_id,u.city_id from ".DB_PREFIX."deal_collect as c left join ".DB_PREFIX."deal as d on d.id = c.deal_id LEFT JOIN ".DB_PREFIX."user u ON u.id= d.user_id where d.is_delete=0 and d.publish_wait = 0 and c.user_id = ".$user_id." order by c.create_time desc limit ".$limit;
        $list = $GLOBALS['db']->getAll($sql);
        foreach($list as $k=>$v){
            $list[$k]['is_wait'] = 0;
            if($list[$k]['start_time'] > TIME_UTC){
                $list[$k]['is_wait'] = 1;
                $list[$k]['remain_time'] = $list[$k]['start_time'] - TIME_UTC;
            }
            else{
                $list[$k]['remain_time'] = $list[$k]['start_time'] + $list[$k]['enddate']*24*3600 - TIME_UTC;
            }

            $list[$k]['borrow_amount_format'] = format_price($v['borrow_amount']);
            $list[$k]['borrow_amount_format'] = format_price($v['borrow_amount']/10000)."万";//format_price($deal['borrow_amount']);
            $list[$k]['rate_foramt_w'] = number_format($v['rate'],2)."%";

            $list[$k]['rate_foramt'] = number_format($v['rate'],2);
            //本息还款金额
            $list[$k]['month_repay_money'] = format_price(pl_it_formula($v['borrow_amount'],$v['rate']/12/100,$v['repay_time']));
            //还需多少钱
            $list[$k]['need_money'] = format_price($v['borrow_amount'] - $v['load_money']);
            //百分比
            if($v['deal_status']==4){
                $list[$k]['month_repay_money'] = pl_it_formula($v['borrow_amount'],$v['rate']/12/100,$v['repay_time']);
                $list[$k]['remain_repay_money'] = $list[$k]['month_repay_money'] * $v['repay_time'];
                $list[$k]['progress_point'] =  round($v['repay_money']/$list[$k]['remain_repay_money']*100,2);
            }else{
                $list[$k]['progress_point'] = $v['load_money']/$v['borrow_amount']*100;
            }

            $user_location = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."region_conf where id = ".intval($v['city_id']),false);
            if($user_location=='')
                $user_location = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."region_conf where id = ".intval($v['province_id']),false);

            $list[$k]['user_location'] = $user_location;
            $list[$k]['point_level'] = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."user_level where id = ".intval($v['level_id']));

            $durl = "/index.php?ctl=deal&act=mobile&is_sj=1&id=".$v['id'];
            $list[$k]['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.$durl);
        }
    }

    return array("list"=>$list,'count'=>$count);
}

function getInvestList($mode = "index", $user_id = 0, $page = 0,$user_name='',$user_pwd='') {

    if ($user_id > 0){
        $condtion = "   AND d.deal_status in(1,2,3,4,5)  ";
        switch($mode){
            case "index" :
                $condtion = "   AND d.deal_status in(1,2,3,4,5)  ";
                break;
            case "invite" :
                $condtion = "   AND d.deal_status in(1,2)  ";
                break;
            case "in" :
                $condtion = "   AND d.deal_status =1  ";
                break;
            case "full" :
                $condtion = "   AND d.deal_status =2  ";
                break;
            case "flow" :
                $condtion = "   AND d.deal_status =3  ";
                break;
            case "ing" :
                $condtion = "   AND d.deal_status =4  ";
                break;
            case "over" :
                $condtion = "   AND d.deal_status =5  ";
                break;
            case "bad" :
                $condtion = "   AND d.deal_status = 4 AND (".TIME_UTC." - d.next_repay_time)/24/3600 >=".trim(app_conf("YZ_IMPSE_DAY"))." and d.last_repay_time > 0 ";
                break;
        }

        if($page==0)
            $page = 1;
        $limit = (($page-1)*app_conf("PAGE_SIZE")).",".app_conf("PAGE_SIZE");
//$sql_count = "select count(DISTINCT dl.id) from ".DB_PREFIX."deal d left join ".DB_PREFIX."deal_load as dl on d.id = dl.deal_id where d.is_delete=0 and d.publish_wait = 0 and dl.user_id = ".$user_id." $condtion ";

        $sql = "select dlt.t_user_id,fcp.is_fangkuan,d.*,u.user_name,dl.money as u_load_money,dl.contract_id as contract_id, dl.download_url as download_url, dl.has_auth as has_auth,u.level_id,u.province_id,u.city_id,dl.id as load_id,dl.rebate_money,dl.ecv_id,dl.interestrate_id,dl.interestrate_money,i.rate as interestrate_rate,e.money as ecv_money 
        from ".DB_PREFIX."deal_load as dl left join  ".DB_PREFIX."deal d on d.id = dl.deal_id 
        LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt on dlt.load_id = dl.id 
        LEFT JOIN ".DB_PREFIX."fuioupay_cp_transaction as fcp ON  dl.id = fcp.deal_load_id
        LEFT JOIN ".DB_PREFIX."user u ON u.id=d.user_id 
        left join ".DB_PREFIX."interestrate i on dl.interestrate_id = i.id 
        left join ".DB_PREFIX."ecv e on dl.ecv_id = e.id 
        where d.is_effect=1 and d.is_delete=0 and d.publish_wait = 0 
        and (dl.user_id = ".$user_id." or dlt.t_user_id =".$user_id.")  
        $condtion 
        group by dl.id 
        order by dl.create_time desc 
        limit ".$limit;

        $sql_count = "select count(DISTINCT dl.id) from ".DB_PREFIX."deal_load as dl left join ".DB_PREFIX."deal d on d.id = dl.deal_id LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt on dlt.load_id = dl.id where d.is_effect=1 and d.is_delete=0 and d.publish_wait = 0 and (dl.user_id = ".$user_id." or dlt.t_user_id =".$user_id.")  $condtion ";

        $count = $GLOBALS['db']->getOne($sql_count);
        $list = array();
        if($count >0){
            $list = $GLOBALS['db']->getAll($sql);
            $load_ids = array();
            foreach($list as $k=>$v){
                $list[$k]['borrow_amount_format'] = format_price($v['borrow_amount']/10000)."万";//format_price($deal['borrow_amount']);
                $list[$k]['rate_foramt_w'] = number_format($v['rate'],2)."%";

                //$list[$k]['borrow_amount_format'] = format_price($v['borrow_amount']);
                $list[$k]['rate_foramt'] = number_format($v['rate'],2);
                $list[$k]['contract_id'] = $v['contract_id'];
                $list[$k]['has_auth'] = $v['has_auth'];

                $list[$k]['u_load_money_format'] =  app_conf("CURRENCY_UNIT")."".number_format($list[$k]['u_load_money']/10000,3)."万";

                //本息还款金额
                $list[$k]['month_repay_money'] = pl_it_formula($v['borrow_amount'],$v['rate']/12/100,$v['repay_time']);
                $list[$k]['month_repay_money_format'] =  format_price($list[$k]['month_repay_money']);

                if($list[$k]['create_time'] !=""){
                    $list[$k]['create_time_format'] =  to_date($list[$k]['create_time'],"Y-m-d");
                }

                if($list[$k]['start_time'] !=""){
                    $list[$k]['start_time_format'] =  to_date($list[$k]['start_time'],"Y-m-d");
                }

                if($v['deal_status'] == 1){
                    //还需多少钱
                    $list[$k]['need_money'] = format_price($v['borrow_amount'] - $v['load_money']);

                    //百分比
                    $list[$k]['progress_point'] = $v['load_money']/$v['borrow_amount']*100;

                }
                elseif($v['deal_status'] == 2 || $v['deal_status'] == 5)
                {
                    $list[$k]['progress_point'] = 100;
                }
                elseif($v['deal_status'] == 4){
                    //百分比
                    $list[$k]['remain_repay_money'] = $list[$k]['month_repay_money'] * $v['repay_time'];
                    //还有多少需要还
                    $list[$k]['need_remain_repay_money'] = $list[$k]['remain_repay_money'] - $v['repay_money'];
                    //还款进度条
                    $list[$k]['progress_point'] =  round($v['repay_money']/$list[$k]['remain_repay_money']*100,2);
                }

                $user_location = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."region_conf where id = ".intval($v['city_id']),false);
                if($user_location=='')
                    $user_location = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."region_conf where id = ".intval($v['province_id']),false);

                $list[$k]['user_location'] = $user_location;
                $list[$k]['point_level'] = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."user_level where id = ".intval($v['level_id']));


                //$durl = url("index","deal",array("id"=>$list[$k]['id']));
                //$deal['url'] = $durl;
//					if($v['deal_status'] == 4 || $v['deal_status'] == 5){
//						$durl = "/index.php?ctl=uc_invest&act=mrefdetail&is_sj=1&id=".$v['id']."&load_id=".$v['load_id']."&user_name=".$user_name."&user_pwd=".$user_pwd;
//						$list[$k]['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.$durl);
//					}else{
                $durl = "/index.php?ctl=deal&act=mobile&is_sj=1&id=".$v['id'];
                $list[$k]['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.$durl);
//					}
                $load_ids[] = $v['load_id'];
            }
            //判断是否已经转让
            if(count($load_ids) > 0){
                $tmptransfer_list  = $GLOBALS['db']->getAll("SELECT * FROM ".DB_PREFIX."deal_load_transfer where load_id in(".implode(",",$load_ids).") and t_user_id > 0 and user_id=".$user_id);
                $transfer_list = array();
                foreach($tmptransfer_list as $k=>$v){
                    $transfer_list[$v['load_id']] = $v;
                }
                unset($tmptransfer_list);
                foreach($list as $k=>$v){
                    if(isset($transfer_list[$v['load_id']])){
                        $list[$k]['has_transfer'] = 1;
                    }
                }
            }

        }


        return array('list'=>$list,'count'=>$count);
    }else{
        return array();
    }

}
//查询会员日志
function get_user_log($limit,$user_id,$t='')
{
    if(!in_array($t,array("money","score","point")))
    {
        $t = "";
    }
    if($t=='')
    {
        $condition = "";
    }
    else
    {
        $condition = " and ".$t." <> 0 ";
    }

    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_log where user_id = ".$user_id." $condition");
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_log where user_id = ".$user_id." $condition order by log_time desc limit ".$limit);
    return array("list"=>$list,'count'=>$count);
}

/**
 * 会员资金日志
 * $limit 数量
 * $user_id 用户id
 * $status -1全部
 * $condition 其他条件
 */
function get_user_money_log($limit,$user_id,$type=-1,$condition){
    $extWhere = "";
    if($type >= 0){
        $extWhere.=" AND `type`=".$type;
    }

    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_money_log where user_id = ".$user_id." $extWhere $condition");
    $list = array();
    if($count > 0){

        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_money_log where user_id = ".$user_id." $extWhere $condition order by id desc limit ".$limit);
    }
    return array("list"=>$list,'count'=>$count);
}

/**
 * 会员冻结资金日志
 * $limit 数量
 * $user_id 用户id
 * $status -1全部
 * $condition 其他条件
 */
function get_user_lock_money_log($limit,$user_id,$type=-1,$condition){
    $extWhere = "";
    if($type >= 0){
        $extWhere.=" AND `type`=".$type;
    }

    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_lock_money_log where user_id = ".$user_id." $extWhere $condition");
    $list = array();
    if($count > 0){

        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_lock_money_log where user_id = ".$user_id." $extWhere $condition order by id desc limit ".$limit);
    }
    return array("list"=>$list,'count'=>$count);
}

/**
 * 会员信用积分日志
 * $limit 数量
 * $user_id 用户id
 * $status -1全部
 * $condition 其他条件
 */
function get_user_point_log($limit,$user_id,$type=-1,$condition){
    $extWhere = '';
    if($type >= 0){
        $extWhere.=" AND `type`=".$type;
    }
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_point_log where user_id = ".$user_id." $extWhere  $condition");
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_point_log where user_id = ".$user_id." $extWhere  $condition order by id DESC limit ".$limit);
    return array("list"=>$list,'count'=>$count);
}

/**
 * 会员积分日志
 * $limit 数量
 * $user_id 用户id
 * $status -1全部
 * $condition 其他条件
 */
function get_user_score_log($limit,$user_id,$type=-1,$condition){
    $extWhere = '';
    if($type >= 0){
        $extWhere.=" AND `type`=".$type;
    }
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_score_log where user_id = ".$user_id." $extWhere  $condition");
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_score_log where user_id = ".$user_id." $extWhere  $condition order by id DESC limit ".$limit);
    return array("list"=>$list,'count'=>$count);
}

/**
 * 不可提现资金日志
 * $limit 数量
 * $user_id 用户id
 * $status -1全部
 * $condition 其他条件
 */
function get_user_nmc_amount_log($limit,$user_id,$type=-1,$condition){
    $extWhere = '';
    if($type >= 0){
        $extWhere.=" AND `type`=".$type;
    }
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_money_log where user_id = ".$user_id." $extWhere AND (`type`= 22 OR `type`= 28 OR `type`= 29)  $condition");
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."user_money_log where user_id = ".$user_id." $extWhere AND (`type`= 22 OR `type`= 28 OR `type`= 29)  $condition order by id DESC limit ".$limit);
    return array("list"=>$list,'count'=>$count);
}

//查询会员充值订单
function get_user_incharge($limit,$user_id)
{
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."deal_order where user_id = ".$user_id." and type = 1 and is_delete = 0");
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."deal_order where user_id = ".$user_id." and type = 1 and is_delete = 0 order by create_time desc limit ".$limit);

        foreach($list as $k=>$v)
        {
            $list[$k]['payment_notice'] = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment_notice where order_id = ".$v['id']);
            $list[$k]['payment'] = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment where id = ".$v['payment_id']);
        }
    }
    return array("list"=>$list,'count'=>$count);
}

//new查询会员充值订单日志
function get_user_incharge_log($limit,$user_id,$condition)
{
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."payment_notice pn left join ".DB_PREFIX."payment p on pn.payment_id = p.id where  pn.user_id = ".$user_id."  $condition ");

    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll("select pn.*,name from ".DB_PREFIX."payment_notice pn left join ".DB_PREFIX."payment p on pn.payment_id = p.id  where pn.user_id = ".$user_id."  $condition  order by pn.pay_time desc,pn.id desc limit ".$limit);
        foreach($list as $k=>$v)
        {
            if($list[$k]['is_paid'] == 1){
                $list[$k]['is_paid_format']="已支付";
            }else{
                $list[$k]['is_paid_format']="未支付";
            }
            $list[$k]['create_time_format'] = to_date($list[$k]['create_time'],"Y-m-d");
            $list[$k]['pay_time_format'] = to_date($list[$k]['pay_time'],"Y-m-d");
            $list[$k]['money_format'] = format_price($list[$k]['money']);

        }
    }
    return array("list"=>$list,'count'=>$count);
}

//查询会员提现记录
function get_user_carry($limit,$user_id)
{
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user_carry where user_id = ".$user_id." ");
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll("select uc.*,b.name as bank_name from ".DB_PREFIX."user_carry uc LEFT JOIN ".DB_PREFIX."bank b ON b.id=uc.bank_id  where user_id = ".$user_id." order by create_time desc limit ".$limit);

        foreach($list as $k=>$v)
        {
            if($v['status']==0){
                $list[$k]['status_format'] = "待处理";
            }
            elseif($v['status']==1){
                $list[$k]['status_format'] = "提现成功";
            }
            elseif($v['status']==2){
                $list[$k]['status_format'] = "提现失败";
            }
            elseif($v['status']==3){
                $list[$k]['status_format'] = "待付款";
            }
            elseif($v['status']==4){
                $list[$k]['status_format'] = "已撤销";
            }
        }
    }
    return array("list"=>$list,'count'=>$count);
}

//查询会员的团购券
function get_user_coupon($limit,$user_id,$status=0)
{
    $user_id = intval($user_id);
    $ext_condition = '';
    if($status==1)
    {
        $ext_condition = " and confirm_time = 0 ";
    }
    if($status==2)
    {
        $ext_condition = " and confirm_time <> 0 ";
    }

    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."deal_coupon where user_id = ".$user_id." and is_delete = 0 and is_valid = 1 ".$ext_condition);
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."deal_coupon where user_id = ".$user_id." and is_delete = 0 and is_valid = 1 ".$ext_condition." order by order_id desc limit ".$limit);

        foreach($list as $k=>$v)
        {
            if($GLOBALS['db']->getOne("select forbid_sms from ".DB_PREFIX."deal where id = ".$v['deal_id'])==1)
            {
                //禁止发券时，将已发数改为上限
                $list[$k]['sms_count'] = app_conf("SMS_COUPON_LIMIT");
            }
            $list[$k]['deal_item'] = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_order_item where id = ".$v['order_deal_id']);
        }
    }

    return array("list"=>$list,'count'=>$count);
}


//查询会员订单
function get_user_order($limit,$user_id)
{
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."deal_order where user_id = ".$user_id." and type = 0 and is_delete = 0");
    $list = array();
    if($count >0){
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."deal_order where user_id = ".$user_id." and type = 0 and is_delete = 0 order by create_time desc limit ".$limit);

        foreach($list as $k=>$v)
        {
            $list[$k]['payment_notice'] = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment_notice where order_id = ".$v['id']);
        }
    }
    return array("list"=>$list,'count'=>$count);
}

//查询会员抽奖
function get_user_lottery($limit,$user_id)
{
    $user_id = intval($user_id);
    $count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."lottery where user_id = ".$user_id);
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll("select * from ".DB_PREFIX."lottery where user_id = ".$user_id." order by create_time desc limit ".$limit);

        foreach($list as $k=>$v)
        {
            $list[$k]['deal_name'] = $GLOBALS['db']->getOne("select name from ".DB_PREFIX."deal where id = ".$v['deal_id']);
            $list[$k]['deal_sub_name'] = $GLOBALS['db']->getOne("select sub_name from ".DB_PREFIX."deal where id = ".$v['deal_id']);
            if($v['buyer_id']==0)
            {
                $buyer = $GLOBALS['db']->getOne("select user_name from ".DB_PREFIX."user where id = ".$v['user_id']);
            }
            else
            {
                $buyer = $GLOBALS['db']->getOne("select user_name from ".DB_PREFIX."user where id = ".$v['buyer_id']);
            }
            $list[$k]['buyer'] = $buyer;
        }
    }

    return array("list"=>$list,'count'=>$count);
}

/**
 * 查询会员邀请及返利列表
 * $type 0有效推荐 1无效推荐
 */
function get_invite_list($limit,$user_id,$type=0)
{
    $user_id = intval($user_id);

    $condition = " AND dl.is_has_loans = 1 AND u.user_type in(0,1) ";
    if($type==0){
        if(intval(app_conf("INVITE_REFERRALS_DATE")) > 0){
            $after_year =  next_replay_month(to_timespan(to_date(TIME_UTC,"Y-m-d")),-intval(app_conf("INVITE_REFERRALS_DATE")));
            $condition =" AND u.create_time >= ".$after_year." and dl.create_time  > ".$after_year."  AND dl.user_id > 0 and dl.id > 0";
        }
        else{
            $condition =" AND dl.user_id > 0 and dl.id > 0";
        }
    }
    else
    {
        if(intval(app_conf("INVITE_REFERRALS_DATE")) > 0){
            $after_year =  next_replay_month(to_timespan(to_date(TIME_UTC,"Y-m-d")),-intval(app_conf("INVITE_REFERRALS_DATE")));
            $condition =" AND (u.create_time < ".$after_year." OR dlr.user_id is null ) and (dlr.id is null OR dlr.id = 0) ";
        }
        else{
            $condition =" AND (dlr.user_id is null ) and (dlr.id is null OR dlr.id = 0)";
        }
    }

    $sql_count = "select count(DISTINCT u.id) from ".DB_PREFIX."user u " .
        "LEFT JOIN ".DB_PREFIX."deal_load_repay dlr ON  dlr.t_user_id = 0 AND dlr.user_id =u.id  " .
        "LEFT JOIN ".DB_PREFIX."deal_load_repay dlrr ON dlrr.id=dlr.id AND dlr.t_user_id > 0 AND dlr.t_user_id=u.id  " .
        "LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id=dlr.load_id  " .
        "where u.pid = ".$user_id." $condition ";

    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0){
        $sql = "select u.*,dl.user_id as r_user_id,dl.create_time as r_create_time FROM ".DB_PREFIX."user u " .
            "LEFT JOIN ".DB_PREFIX."deal_load_repay dlr ON  dlr.t_user_id = 0 AND dlr.user_id =u.id  " .
            "LEFT JOIN ".DB_PREFIX."deal_load_repay dlrr ON dlrr.id=dlr.id AND dlr.t_user_id > 0 AND dlr.t_user_id=u.id  " .
            "LEFT JOIN ".DB_PREFIX."deal_load dl ON dl.id=dlr.load_id  " .
            "where u.pid = ".$user_id." $condition group by u.id order by id DESC limit ".$limit;
        $list = $GLOBALS['db']->getAll($sql);
        foreach($list as $k=>$v){
            if(intval($v['r_user_id'])==0){
                $list[$k]['result'] = "未投资";
            }
            elseif(intval($v['create_time'])<$after_year){
                $list[$k]['result'] = "过期";
            }
        }
    }

    return array("list"=>$list,'count'=>$count);
}

/**
 * 授信额度申请
 */
function get_deal_quota_list($limit,$user_id,$condition)
{
    $user_id = intval($user_id);
    $sql = "select * from ".DB_PREFIX."deal_quota_submit  where user_id = ".$user_id." $condition order by id desc limit ".$limit;
    $sql_count = "select count(*) from ".DB_PREFIX."deal_quota_submit  where user_id = ".$user_id." $condition ";
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll($sql);
        foreach($list as $k=>$v){
            if($list[$k]['borrow_amount'] < 100)
                $list[$k]['borrow_amount_format'] = format_price($list[$k]['borrow_amount']);
            else
                $list[$k]['borrow_amount_format'] = format_price($list[$k]['borrow_amount']/10000)."万";

            $list[$k]['create_time_format'] = to_date($v['create_time'],'Y-m-d H:i');
            $list[$k]['update_time_format'] = to_date($v['update_time'],'Y-m-d H:i');
            if($v['status']==0)
                $list[$k]['status_format'] = "未审核";
            elseif($v['status']==1)
                $list[$k]['status_format'] = "已通过";
            elseif($v['status']==2)
                $list[$k]['status_format'] = "未通过";
        }
    }

    return array("list"=>$list,'count'=>$count);
}
//查询信用值申请列表
function get_quota_list($limit,$user_id,$condition)
{
    $user_id = intval($user_id);
    $sql = "select * from ".DB_PREFIX."quota_submit  where user_id = ".$user_id." $condition order by id desc limit ".$limit;
    $sql_count = "select count(*) from ".DB_PREFIX."quota_submit  where user_id = ".$user_id." $condition ";
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0){
        $list = $GLOBALS['db']->getAll($sql);
        foreach($list as $k=>$v){
            $list[$k]['create_time_format'] = to_date($v['create_time'],'Y-m-d H:i');
            $list[$k]['op_time_format'] = to_date($v['op_time'],'Y-m-d H:i');
            if($v['status']==0)
                $list[$k]['status_format'] = "未审核";
            elseif($v['status']==1)
                $list[$k]['status_format'] = "已通过";
            elseif($v['status']==2)
                $list[$k]['status_format'] = "未通过";
        }
    }


    return array("list"=>$list,'count'=>$count);
}


//查询代金券列表
function get_voucher_list($limit,$user_id)
{
    $user_id = intval($user_id);
    $sql = "select e.*,et.name,et.gen_count,et.send_type,et.exchange_score,et.exchange_limit,et.exchange_sn from ".DB_PREFIX."ecv as e left join ".DB_PREFIX."ecv_type as et on e.ecv_type_id = et.id where e.user_id = ".$user_id." order by e.id desc limit ".$limit;
    $sql_count = "select count(*) from ".DB_PREFIX."ecv where user_id = ".$user_id;
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll($sql);

    return array("list"=>$list,'count'=>$count);
}

//查询可兑换代金券列表
function get_exchange_voucher_list($limit)
{
    $sql = "select * from ".DB_PREFIX."ecv_type where send_type = 1 order by id desc limit ".$limit;
    $sql_count = "select count(*) from ".DB_PREFIX."ecv_type where send_type = 1";
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll($sql);

    return array("list"=>$list,'count'=>$count);
}

//查询加息券列表
function get_interestrate_list($limit,$user_id,$type=0)
{
    $user_id = intval($user_id);
    $condition = "";
    if($type==1)
    {
        $condition = " and (et.use_type = 1 or et.use_type = 2) ";
    }
    else
    {
        //$condition = " and use_type = 0 ";
    }
    $sql = "select *,e.id as i_id from ".DB_PREFIX."interestrate as e left join ".DB_PREFIX."interestrate_type as et on e.ecv_type_id = et.id where ((e.user_id = ".$user_id." and e.to_user_id = 0) or e.to_user_id = ".$user_id.") ".$condition." order by e.id desc limit ".$limit;

    $sql_count = "select count(*) from ".DB_PREFIX."interestrate e left join ".DB_PREFIX."interestrate_type as et on e.ecv_type_id = et.id where ((e.user_id = ".$user_id." and e.to_user_id = 0) or e.to_user_id = ".$user_id.")".$condition;

    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll($sql);

    foreach($list as $k=>$v)
    {
        $list[$k]["rate_format"] = number_format($v["rate"],2)."%";
        if($v["use_type"] == 0)
        {
            $list[$k]["use_type_name"] = "PC端";
        }
        elseif($v["use_type"] == 1)
        {
            $list[$k]["use_type_name"] = "手机端";
        }
        elseif($v["use_type"] == 2)
        {
            $list[$k]["use_type_name"] = "通用";
        }
    }
    return array("list"=>$list,'count'=>$count);
}

//查询可兑换加息券列表
function get_exchange_interestrate_list($limit)
{
    $sql = "select * from ".DB_PREFIX."interestrate_type where send_type = 1 and (end_time = 0 or end_time >= ".to_timespan(to_date(TIME_UTC,"Y-m-d")).") order by id desc limit ".$limit;
    $sql_count = "select count(*) from ".DB_PREFIX."interestrate_type where send_type = 1 and (begin_time = 0 or begin_time <= ".to_timespan(to_date(TIME_UTC,"Y-m-d")).") and (end_time = 0 or end_time >= ".to_timespan(to_date(TIME_UTC,"Y-m-d")).")";
    $count = $GLOBALS['db']->getOne($sql_count);
    $list = array();
    if($count > 0)
        $list = $GLOBALS['db']->getAll($sql);
    foreach($list as $k=>$v)
    {
        $list[$k]["rate_format"] = number_format($v["rate"],2)."%";
        if($v["use_type"] == 0)
        {
            $list[$k]["use_type_name"] = "PC端";
        }
        elseif($v["use_type"] == 1)
        {
            $list[$k]["use_type_name"] = "手机端";
        }
        elseif($v["use_type"] == 2)
        {
            $list[$k]["use_type_name"] = "通用";
        }

        if($v['begin_time'] > 0)
        {
            $list[$k]['begin_date'] = to_date($v['begin_time'],"Y-m-d");
        }
        else
        {
            $list[$k]['begin_date'] = "即时生效";
        }

        if($v['end_time'] > 0)
        {
            $list[$k]['end_date'] = to_date($v['end_time'],"Y-m-d");
        }
        else
        {
            $list[$k]['end_date'] = "永不过期";
        }
    }
    return array("list"=>$list,'count'=>$count);
}


function getUcTransferList($page,$status){
    if($page==0)
        $page = 1;

    $limit = (($page-1)*app_conf("PAGE_SIZE")).",".app_conf("PAGE_SIZE");

    $condition = ' AND if(d.transfer_day > 0 ,(d.repay_start_time + d.transfer_day*24*3600 + 24*3600 )< '.TIME_UTC.'  ,"1=1") and d.is_effect=1 and d.is_delete=0  and d.repay_time_type =1 and  d.publish_wait=0 and dl.user_id='.$GLOBALS['user_info']['id']."  ";
    $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id and dlt.load_id=dl.id ";
    switch($status){
        case 1://可转让
            $condition.=" AND d.next_repay_time - ".TIME_UTC." + 24*3600 - 1 > 0 AND d.deal_status = 4 and (isnull(dlt.id) or (dlt.t_user_id =0 and dlt.status = 0) ) ";
            break;
        case 2://转让中
            $condition.=" AND d.deal_status = 4 AND dlt.status = 1 and dlt.user_id >0 and dlt.t_user_id=0 ";
            break;
        case 3://已转让
            $condition.=" AND dlt.t_user_id > 0 ";
            break;
        case 4://已撤销
            $condition.=" AND dlt.status = 0 ";
            break;
        default ://默认
            $condition.=" AND ((d.deal_status = 4 and dlt.id > 0) or (d.deal_status = 4 and isnull(dlt.id) AND d.next_repay_time - ".TIME_UTC." + 24*3600 - 1 > 0)  or (d.deal_status = 5 and dlt.id >0))";
            break;
    }

    $count_sql = 'SELECT count(dl.id) FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $rs_count = $GLOBALS['db']->getOne($count_sql);
    if($rs_count > 0){
        $list_sql = 'SELECT dl.id as dlid,d.*,dlt.near_repay_time,dl.money as load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time,dl.learn_id,dl.learn_money FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 and dl.learn_id = 0 '.$condition.' ORDER BY d.id DESC';

        $list = $GLOBALS['db']->getAll($list_sql." LIMIT $limit ");
        foreach($list as $k => $v){
            //最后还款日
            $list[$k]['final_repay_time'] = next_replay_month($v['repay_start_time'],$v['repay_time']);

            $list[$k]['final_repay_time_format'] = to_date($list[$k]['final_repay_time'],"Y-m-d");
            //剩余期数
            if(intval($v['t_user_id']) > 0){
                $list[$k]['how_much_month'] = how_much_month($v['near_repay_time'],$list[$k]['final_repay_time']);
                if(is_last_repay($v['loantype'])==2){
                    $list[$k]['how_much_month'] =  $list[$k]['how_much_month'] / 3;
                }
            }
            elseif($v['deal_status']==4)
            {
                if($v['last_repay_time'] > 0)
                    $list[$k]['how_much_month'] = how_much_month($v['last_repay_time'],$list[$k]['final_repay_time']);
                else
                    $list[$k]['how_much_month'] = how_much_month($v['repay_start_time'],$list[$k]['final_repay_time']);

                if(is_last_repay($v['loantype'])==2){
                    $list[$k]['how_much_month'] =  $list[$k]['how_much_month'] / 3;
                }
            }
            else{
                $list[$k]['how_much_month'] = 0;
            }

            $transfer_rs = deal_transfer($list[$k]);
            $list[$k]['month_repay_money'] = $transfer_rs['month_repay_money'];
            $list[$k]['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
            $list[$k]['left_benjin'] = round($transfer_rs['left_benjin'],2);

            $list[$k]['learn_id'] = $v['learn_id'];

            $list[$k]['left_benjin_format'] = format_price($list[$k]['left_benjin']);
            //剩多少利息
            $list[$k]['left_lixi'] = $list[$k]['all_must_repay_money'] - $list[$k]['left_benjin'];
            $list[$k]['left_lixi_format'] = format_price($list[$k]['left_lixi']);

            //转让价格
            $list[$k]['transfer_amount_format'] =  format_price($v['transfer_amount']/10000)."万";

            if($v['tras_create_time'] !=""){
                $list[$k]['tras_create_time_format'] =  to_date($v['tras_create_time'],"Y-m-d");
            }

            $list[$k]['near_repay_time_format'] =  to_date($v['near_repay_time'],"Y-m-d");

            if ($list[$k]['tras_status'] == ''){
                if($list[$k]['learn_id']==0){
                    $list[$k]['tras_status_format'] = '可转让';
                }else{
                    $list[$k]['tras_status_format'] = '不可转让';
                }
            }
            else if ($list[$k]['tras_status'] == 0)
                $list[$k]['tras_status_format'] = '已撤销';
            else if ($list[$k]['tras_status'] == 1){
                if ($list[$k]['t_user_id'] > 0){
                    $list[$k]['tras_status_format'] = '已转让';
                }else{
                    $list[$k]['tras_status_format'] = '转让中';
                }
            }

            $list[$k]['tras_status_op'] = 0;

            if ($list[$k]['tras_status'] == '')
                $list[$k]['tras_status_op'] = 1;//'转让';//<a href="javascript:void(0);" class="J_do_transfer" dataid="{$item.dlid}">转让</a>
            else if ($list[$k]['tras_status'] == 0){
                if ($list[$k]['how_much_month'] == 0)
                    $list[$k]['tras_status_op'] = 2;//'还款完毕,无法转让';
                else{
                    if ($list[$k]['next_repay_time'] +24*3600-1 - TIME_UTC < 0)
                        $list[$k]['tras_status_op'] = 3;//'逾期还款,无法转让';
                    else
                        $list[$k]['tras_status_op'] = 4;//'重转让';//<a href="javascript:void(0);" class="J_do_transfer" dataid="{$item.dlid}">重转让</a>
                }
            }
            else if ($list[$k]['tras_status'] == 1){
                if ($list[$k]['t_user_id'] > 0){
                    $list[$k]['tras_status_op'] = 5;//'查看详情<br>转让协议';
                    //<a href="{url x="index" r="transfer#detail" p="id=$item.dltid"}">查看详情</a><br>
                    //<a href="javascript:void(0);" onclick="javascript:window.showModalDialog('{url x="index" r="uc_transfer#contact" p="id=$item.dltid"}');">转让协议</a>
                }else
                    $list[$k]['tras_status_op'] = 6;//'撤销';//<a href="javascript:void(0);"  class="J_do_reback" dataid="{$item.dltid}">撤销</a>
            }

            if(is_last_repay($v['loantype'])==2){
                $list[$k]['repay_time'] =  $list[$k]['repay_time'] / 3;
            }

            $durl = "/index.php?ctl=deal&act=mobile&is_sj=1&id=".$v['id'];
            $list[$k]['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.$durl);
        }

        return array('list'=>$list,'count'=>$rs_count);
    }else{
        return array('list'=>null,'count'=>0);
    }
}

//转让;
function getUcToTransfer($id,$tid){

    $status = array('status'=>0,'show_err'=>'','transfer');
    if($id==0){
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权";
        return $status;
    }

    $learn_id = $GLOBALS['db']->getOne("SELECT learn_id FROM ".DB_PREFIX."deal_load WHERE id=".$id);
    if($learn_id > 0){
        $status['status'] = 0;
        $status['show_err'] = "体验金投资，不可转让";
        return $status;
    }

    //先执行更新借贷信息
    $deal_id = $GLOBALS['db']->getOne("SELECT deal_id FROM ".DB_PREFIX."deal_load WHERE id=".$id);
    if($deal_id==0){
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权";
        return $status;
    }
    else{
        syn_deal_status($deal_id);
    }

    $condition = ' AND if(d.transfer_day > 0 ,(d.repay_start_time + d.transfer_day*24*3600 + 24*3600 )< '.TIME_UTC.'  ,"1=1") AND dl.id='.$id.' AND d.deal_status = 4 and d.is_effect=1 and d.is_delete=0  and d.repay_time_type =1 and  d.publish_wait=0 and dl.user_id='.$GLOBALS['user_info']['id']."  and d.next_repay_time - ".TIME_UTC." + 24*3600 - 1 > 0  ";
    if($tid > 0)
    {
        $condition.=" and dlt.id=$tid";
    }

    $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id and dlt.load_id=dl.id ";

    $sql = 'SELECT dl.id as dlid,d.*,dlt.near_repay_time,dl.money as load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $transfer = $GLOBALS['db']->getRow($sql);

    if($transfer){
        //下个还款日
        if(intval($transfer['next_repay_time']) > 0){
            $transfer['next_repay_time_format'] = to_date($transfer['next_repay_time'],"Y-m-d");
        }
        else{
            $transfer['next_repay_time_format'] = to_date(next_replay_month($transfer['repay_start_time']),"Y-m-d");
        }


        //还款日
        $transfer['final_repay_time'] = next_replay_month($transfer['repay_start_time'],$transfer['repay_time']);
        $transfer['final_repay_time_format'] = to_date($transfer['final_repay_time'],"Y-m-d");
        //剩余期数
        if(intval($transfer['t_user_id']) > 0){
            $transfer['how_much_month'] = how_much_month($transfer['near_repay_time'],$transfer['final_repay_time']);
            if(is_last_repay($transfer['loantype'])==2){
                $transfer['how_much_month'] =  $transfer['how_much_month'] / 3;
            }
        }
        elseif($transfer['deal_status']==4){
            if($transfer['last_repay_time'] > 0)
                $transfer['how_much_month'] = how_much_month($transfer['last_repay_time'],$transfer['final_repay_time']);
            else
                $transfer['how_much_month'] = how_much_month($transfer['repay_start_time'],$transfer['final_repay_time']);

            if(is_last_repay($transfer['loantype'])==2){
                $transfer['how_much_month'] =  $transfer['how_much_month'] / 3;
            }
        }
        else{
            $transfer['how_much_month'] = 0;
        }


        $transfer_rs = deal_transfer($transfer);
        $transfer['month_repay_money'] = $transfer_rs['month_repay_money'];
        $transfer['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
        $transfer['left_benjin'] = $transfer_rs['left_benjin'];

        $transfer['left_benjin_format'] = format_price($transfer['left_benjin']);
        //剩多少利息
        $transfer['left_lixi'] = $transfer['all_must_repay_money'] - $transfer['left_benjin'];
        $transfer['left_lixi_format'] = format_price($transfer['left_lixi']);

        //转让价格
        $transfer['transfer_amount_format'] =  format_price($transfer['all_must_repay_money']);

        if($transfer['tras_create_time'] !=""){
            $transfer['tras_create_time_format'] =  to_date($transfer['tras_create_time'],"Y-m-d");
        }

        if(is_last_repay($transfer['loantype'])==2){
            $transfer['repay_time'] =  $transfer['repay_time'] / 3;
        }

        $status['status'] = 1;
        $status['transfer'] = $transfer;
        $status['show_err'] = "";
        return $status;
    }
    else{
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权转让";
        return $status;
    }
}

/**
 * 执行转让
 */
function getUcDoTransfer($id,$tid,$paypassword,$transfer_money){
    $paypassword = strim($paypassword);
    $id = intval($id);
    $tid = intval($tid);
    $transfer_money = floatval($transfer_money);

    $status = array('status'=>0,'show_err'=>'');
    if($id==0){
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权";
        return $status;
    }

    if($transfer_money <= 0){
        $status['status'] = 0;
        $status['show_err'] = "转让金额必须大于0";
        return $status;
    }

    $deal_id = $GLOBALS['db']->getOne("SELECT deal_id FROM ".DB_PREFIX."deal_load WHERE id=".$id);
    if($deal_id==0){
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权";
        return $status;
    }
    else{
        syn_deal_status($deal_id);
    }

    //判断支付密码是否正确
    if($paypassword ==""){
        $status['status'] = 0;
        $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
        return $status;
    }

    if(md5($paypassword) != $GLOBALS['user_info']['paypassword']){
        $status['status'] = 0;
        $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_ERROR'];
        return $status;
    }

    $condition = ' AND if(d.transfer_day > 0 ,(d.repay_start_time + d.transfer_day*24*3600 + 24*3600 )< '.TIME_UTC.'  ,"1=1") AND dl.id='.$id.' AND d.deal_status = 4 and d.is_effect=1 and d.is_delete=0 and d.repay_time_type =1 and  d.publish_wait=0 and dl.user_id='.$GLOBALS['user_info']['id']." and d.next_repay_time - ".TIME_UTC." + 24*3600 - 1 > 0  ";
    $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id and dlt.load_id=dl.id ";

    $sql = 'SELECT dl.id as dlid,d.*,dl.money as load_money,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $transfer = $GLOBALS['db']->getRow($sql);

    if($transfer){

        //下个还款日
        if(intval($transfer['next_repay_time']) == 0){
            $transfer['next_repay_time'] = next_replay_month($transfer['repay_start_time']);
        }

        if($transfer['next_repay_time'] - TIME_UTC + 24*3600 -1 < 0){
            $status['status'] = 0;
            $status['show_err'] = "转让操作失败，有逾期未还款存在！";
            return $status;
        }

        //还款日
        $transfer['final_repay_time'] = next_replay_month($transfer['repay_start_time'],$transfer['repay_time']);

        //剩余期数
        if(intval($transfer['last_repay_time']) > 0)
            $transfer['how_much_month'] = how_much_month($transfer['last_repay_time'],$transfer['final_repay_time']);
        else{
            $transfer['how_much_month'] = how_much_month($transfer['repay_start_time'],$transfer['final_repay_time']);
        }

        if(is_last_repay($transfer['loantype'])==2){
            $transfer['how_much_month'] =  $transfer['how_much_month'] / 3;
        }

        $transfer_rs = deal_transfer($transfer);
        $transfer['month_repay_money'] = $transfer_rs['month_repay_money'];
        $transfer['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
        $transfer['left_benjin'] = $transfer_rs['left_benjin'];

        //剩多少利息
        $transfer['left_lixi'] = $transfer['all_must_repay_money'] - $transfer['left_benjin'];

        //判断转让金额是否超出了可转让的界限
        if(round($transfer_money,2) > round(floatval($transfer['all_must_repay_money']),2)){
            $status['status'] = 0;
            $status['show_err'] = "转让金额不得大于最大转让金额";
            return $status;
        }

        $transfer_data['create_time'] = TIME_UTC;
        $transfer_data['create_date'] = to_date(TIME_UTC);
        $transfer_data['deal_id'] = $transfer['id'];
        $transfer_data['load_id'] = $transfer['dlid'];
        $transfer_data['user_id'] = $GLOBALS['user_info']['id'];
        $transfer_data['transfer_number'] = $transfer['how_much_month'];
        $transfer_data['last_repay_time'] = $transfer['final_repay_time'];
        $transfer_data['load_money'] = $transfer['load_money'];
        $transfer_data['status'] = 1;
        $transfer_data['transfer_amount'] = $transfer_money;
        $transfer_data['near_repay_time'] = is_last_repay($transfer['loantype']) == 1 ? $transfer['next_repay_time'] : ($transfer['last_repay_time'] > 0 ? $transfer['last_repay_time'] : $transfer['repay_start_time']);

        if($tid > 0){
            $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_transfer",$transfer_data,"UPDATE","id=".$tid);
        }
        else{
            $tid =  $GLOBALS['db']->getOne("SELECT id FROM ".DB_PREFIX."deal_load_transfer  WHERE deal_id='".$transfer['id']."' AND  load_id= '".$transfer['dlid']."' and user_id='".$GLOBALS['user_info']['id']."'  ");
            if($tid){
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_transfer",$transfer_data,"UPDATE","id=".$tid);
            }
            else{
                $GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_transfer",$transfer_data);
            }
        }

        if($GLOBALS['db']->affected_rows()){
            $status['status'] = 1;
            $status['show_err'] = "转让操作成功";
            return $status;
        }
        else{
            $status['status'] = 0;
            $status['show_err'] = "转让操作失败";
            return $status;
        }
    }
    else{
        $status['status'] = 0;
        $status['show_err'] = "不存在的债权";
        return $status;
    }
}

function getUcTransferBuys($page,$status){
    if($page==0)
        $page = 1;

    $limit = (($page-1)*app_conf("PAGE_SIZE")).",".app_conf("PAGE_SIZE");
    $page_args= array();

    $condition = ' and d.is_effect=1 and d.is_delete=0  and d.repay_time_type =1 and  d.publish_wait=0 and dlt.t_user_id='.$GLOBALS['user_info']['id']."  ";
    $union_sql = " LEFT JOIN ".DB_PREFIX."deal_load_transfer dlt ON dlt.deal_id = dl.deal_id  and dlt.load_id=dl.id ";
    switch($status){
        case 1://回收中
            $condition.= " AND d.deal_status = 4 ";
            break;
        case 2://已回收
            $condition.=" AND d.deal_status = 5 ";
            break;
        default ://默认
            $condition.=" AND d.deal_status >= 4 ";
            break;
    }

    $count_sql = 'SELECT count(dl.id) FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition;

    $rs_count = $GLOBALS['db']->getOne($count_sql." LIMIT $limit ");
    $list = array();
    if($rs_count > 0){
        $list_sql = 'SELECT dl.id as dlid,d.*,dl.money as load_money,dlt.id as dltid,dlt.status as tras_status,dlt.t_user_id,dlt.transfer_amount,dlt.create_time as tras_create_time,dlt.transfer_time FROM '.DB_PREFIX.'deal_load dl LEFT JOIN '.DB_PREFIX.'deal d ON d.id = dl.deal_id '.$union_sql.' WHERE 1=1 '.$condition." ORDER BY dlid DESC";

        $list = $GLOBALS['db']->getAll($list_sql);
        foreach($list as $k => $v){
            //最后还款日
            $list[$k]['final_repay_time'] = next_replay_month($v['repay_start_time'],$v['repay_time']);
            $list[$k]['final_repay_time_format'] = to_date($list[$k]['final_repay_time'],"Y-m-d");
            //剩余期数
            if($v['deal_status']==4){
                if(intval($v['last_repay_time']) > 0)
                    $list[$k]['how_much_month'] = how_much_month($v['last_repay_time'],$list[$k]['final_repay_time']);
                else{
                    $list[$k]['how_much_month'] = how_much_month($v['repay_start_time'],$list[$k]['final_repay_time']);
                }

                if(is_last_repay($v['loantype'])==2){
                    $list[$k]['how_much_month'] = $list[$k]['how_much_month'] / 3;
                }
            }
            else{
                $list[$k]['how_much_month'] = 0;
            }

            $transfer_rs = deal_transfer($list[$k]);
            $list[$k]['month_repay_money'] = $transfer_rs['month_repay_money'];



            if($v['deal_status']==4){

                $transfer_rs = deal_transfer($list[$k]);
                //剩余多少钱未回
                $list[$k]['all_must_repay_money'] = $transfer_rs['all_must_repay_money'];
                $list[$k]['left_benjin'] = $transfer_rs['left_benjin'];

                $list[$k]['left_benjin_format'] = format_price($list[$k]['left_benjin']/10000)."万";
                //剩多少利息
                $list[$k]['left_lixi'] = $list[$k]['all_must_repay_money'] - $list[$k]['left_benjin'];
                $list[$k]['left_lixi_format'] = format_price($list[$k]['left_lixi']);

            }
            else{
                $list[$k]['left_benjin_format'] = format_price(0);
                $list[$k]['left_lixi_format'] = format_price(0);
            }

            //转让价格
            $list[$k]['transfer_amount_format'] =  format_price($v['transfer_amount']/10000,3)."万";

            if($v['tras_create_time'] !=""){
                $list[$k]['tras_create_time_format'] =  to_date($v['tras_create_time'],"Y-m-d");
            }

            if(intval($v['transfer_time'])>0){
                $list[$k]['transfer_time_format'] =  to_date($v['transfer_time'],"Y-m-d");
            }

            if(is_last_repay($v['loantype'])==2){
                $list[$k]['repay_time'] = $list[$k]['repay_time'] / 3;
            }

            $list[$k]['tras_status_op'] = 5;
            if($v['deal_status']==4)
                $list[$k]['tras_status_format'] = '回收中';
            elseif($v['deal_status']==5)
                $list[$k]['tras_status_format'] = '已回收';

            $durl = "/index.php?ctl=deal&act=mobile&is_sj=1&id=".$v['id'];
            $list[$k]['app_url'] = str_replace("/mapi", "", SITE_DOMAIN.$durl);
        }

        return array('list'=>$list,'count'=>$rs_count);
    }else{
        return array('list'=>null,'count'=>0);
    }
}


function getInchargeDone($payment_id,$money,$bank_id,$memo,$pingzheng,$debit_id = 0,$debit_type = 0)
{
    $status = array('status'=>0,'show_err'=>'');

    if($money<=0)
    {
        $status['status'] = 0;
        $status['show_err'] = $GLOBALS['lang']['PLEASE_INPUT_CORRECT_INCHARGE'];
        return $status;
    }

    $payment_info = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."payment where id = ".$payment_id);
    if(!$payment_info)
    {
        $status['status'] = 0;
        $status['show_err'] = $GLOBALS['lang']['PLEASE_SELECT_PAYMENT'];
        return $status;
    }

    $order = array();
    $order['payment_id'] = $payment_id;
    $order['bank_id'] = $bank_id;
    $order['memo'] = $memo;

    //开始生成订单
    $now = TIME_UTC;

    $order['user_type'] = 0;
    $order['user_id'] = $GLOBALS['user_info']['id'];
    $order['create_time'] = $now;
    $order['create_date'] = to_date(TIME_UTC,"Y-m-d");

    //VIP 会员则按照VIP充值手续费配置
    $vip_id = $GLOBALS['user_info']['vip_id'];
    if($vip_id>0){
        $interface_class = $payment_info['class_name'];
        $recharge_info = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."user_recharge_config WHERE interface_class='$interface_class' and vip_id = ".$vip_id);
        if($recharge_info){
            $payment_info['fee_type'] = $recharge_info['fee_type'];
            $payment_info['fee_amount'] = $recharge_info['fee'];
        }
    }

    if($payment_info['fee_type'] == 0)
        $order['money'] = $money + $payment_info['fee_amount'];
    else
        $order['money'] = $money + $payment_info['fee_amount']*$money;

    //收用户手续费
    if($payment_info['fee_type'] == 0)
        $order['fee_amount'] = $payment_info['fee_amount'];
    else
        $order['fee_amount'] = $payment_info['fee_amount']*$money;

    /*支付手续费
    if($payment_info['pay_fee_type'] == 0)
        $order['pay_fee_amount'] = $payment_info['pay_fee_amount'];
    else
        $order['pay_fee_amount'] = $payment_info['pay_fee_amount']*$money;
    */

    if($payment_info['class_name']=='Otherpay'){

        $payment_info['config'] = unserialize($payment_info['config']);
        if($order['memo']==""){
            $status['status'] = 0;
            $status['show_err'] = "请输入银行流水单号";
            return $status;
        }

        if($order['bank_id']==""){
            $status['status'] = 0;
            $status['show_err'] = "请选择开户行";
            return $status;
        }


        $order['outer_notice_sn'] =  $order['memo'];//银行流水号

        $order['memo'] = "银行流水单号:".$order['memo'];
        $order['memo'] .= "<br>开户行：".$payment_info['config']['pay_bank'][$order['bank_id']];
        $order['memo'] .= "<br>充值银行：".$payment_info['config']['pay_name'][$order['bank_id']];
        $order['memo'] .= "<br>帐号：".$payment_info['config']['pay_account'][$order['bank_id']];
        $order['memo'] .= "<br>用户：".$payment_info['config']['pay_account_name'][$order['bank_id']];
        if($pingzheng!="")
            $order['memo'] .= "<br>凭证：<a href='".$pingzheng."' target='_blank'>查看</a>";

        //$order['bank_id'] = $payment_info['config']['pay_account'][$order['bank_id']];//银行帐户
    }
    if($debit_id > 0)
    {
        $order['order_id'] = intval($debit_id);
    }
    if($debit_type > 0)
    {
        $order['debit_type'] = intval($debit_type);
    }

    do
    {
        $order['notice_sn'] = to_date(TIME_UTC,"Ymdhis").rand(100,999);

        $GLOBALS['db']->autoExecute(DB_PREFIX."payment_notice",$order,'INSERT','','SILENT');
        $order_id = intval($GLOBALS['db']->insert_id());
    }
    while($order_id==0);


    $status['payment_info'] = $payment_info;
    $status['status'] = 1;
    $status['payment_notice_id'] = $order_id;
    $status['order_id'] = $order_id;
    $status['pay_status'] = 0;

    return $status;
}

//用户提现;
function getUcSaveCarry($amount,$paypassword,$bid){
    $status = array('status'=>0,'show_err'=>'');

    if($GLOBALS['user_info']['id'] > 0){

        $paypassword = strim($paypassword);
        $amount = floatval($amount);
        $bid = intval($bid);

        if($paypassword==""){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
            return $status;
        }

        if(md5($paypassword)!=$GLOBALS['user_info']['paypassword']){
            $status['status'] = 0;
            $status['show_err'] = '密码不正确';
            return $status;
        }

        if(get_user_info("is_black","id=".$GLOBALS['user_info']['id'],"ONE")==1){
            $status['status'] = 0;
            $status['show_err'] = "您当前无权限提现，具体联系网站客服";
            return $status;
        }

        $data['user_id'] = intval($GLOBALS['user_info']['id']);
        $data['money'] = $amount;

        if($data['money'] <=0)
        {
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['CARRY_MONEY_NOT_TRUE'].'-';
            return $status;
        }

        $fee = getCarryFee($data['money'],$GLOBALS['user_info']);

        //判断提现金额限制
        if(($data['money'] + $fee + floatval($GLOBALS['user_info']['nmc_amount'])) > floatval($GLOBALS['user_info']['money'])){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['CARRY_MONEY_NOT_ENOUGHT'];
            return $status;
        }
        $data['fee'] = $fee;


        if($bid == 0)
        {
            $status['status'] = 0;
            $status['show_err'] = '请选择银行';//$GLOBALS['lang']['PLASE_ENTER_CARRY_BANK'];
            return $status;
        }

        $yu_money = get_user_info("ROUND(AES_DECRYPT(money_encrypt,'".AES_DECRYPT_KEY."'),2) - nmc_amount","id=".intval($GLOBALS['user_info']['id']),"ONE_encrypt") ;

        //更新会员账户信息
        if((floatval($fee) + floatval($data['money'])) <= $yu_money){

            $user_bank = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."user_bank where user_id=".intval($GLOBALS['user_info']['id'])." AND id=$bid ");

            $data['bank_id'] = $user_bank['bank_id'];
            $data['real_name'] = $user_bank['real_name'];
            $data['region_lv1'] = intval($user_bank['region_lv1']);
            $data['region_lv2'] = intval($user_bank['region_lv2']);
            $data['region_lv3'] = intval($user_bank['region_lv3']);
            $data['region_lv4'] = intval($user_bank['region_lv4']);
            $data['bankzone'] = trim($user_bank['bankzone']);
            $data['bankcard'] = trim($user_bank['bankcard']);


            $data['create_time'] = TIME_UTC;
            $data['create_date'] = to_date(TIME_UTC,"Y-m-d");
            $GLOBALS['db']->autoExecute(DB_PREFIX."user_carry",$data,"INSERT");

            require_once APP_ROOT_PATH.'system/libs/user.php';
            modify_account(array('money'=>-$data['money'],'lock_money'=>$data['money']),$data['user_id'],"提现申请",8);
            modify_account(array('money'=>-$fee,'lock_money'=>$fee),$data['user_id'],"提现手续费",9);

            //$content = "您于".to_date($data['create_time'],"Y年m月d日 H:i:s")."提交的".format_price($data['money'])."提现申请我们正在处理，如您填写的账户信息正确无误，您的资金将会于3个工作日内到达您的银行账户.";

            $notice['time']=to_date($data['create_time'],"Y年m月d日 H:i:s");
            $notice['money']=format_price($data['money']);

            $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_WITHDRAWS_CASH'",false);
            $GLOBALS['tmpl']->assign("notice",$notice);
            $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);

            send_user_msg("",$content,0,$data['user_id'],TIME_UTC,0,true,5);

            $status['status'] = 1;
            $status['show_err'] = $GLOBALS['lang']['CARRY_SUBMIT_SUCCESS'];

            return $status;

        }
        else{
            $status['status'] = 0;
            $status['show_err'] = '您的余额不足';//$GLOBALS['lang']['CARRY_MONEY_NOT_ENOUGHT'];
            return $status;
        }

    }else{
        $status['show_err'] ="未登录";
    }
    return $status;
}

//用户提现;
function getAuthorizedSaveCarry($amount,$paypassword,$bid){

    $status = array('status'=>0,'show_err'=>'');

    if($GLOBALS['authorized_info']['id'] > 0){
        $paypassword = strim($paypassword);
        $amount = floatval($amount);
        $bid = intval($bid);
        if($paypassword==""){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
            return $status;
        }
        if(md5($paypassword)!=$GLOBALS['authorized_info']['paypassword']){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_ERROR'];
            return $status;
        }

        $data['user_id'] = intval($GLOBALS['authorized_info']['id']);
        $data['money'] = $amount;

        if($data['money'] <=0)
        {
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['CARRY_MONEY_NOT_TRUE'];
            return $status;
        }
        $fee = 0;
        $feel_type = 0;
        //获取手续费配置表
        $fee_config = load_auto_cache("user_carry_config");
        //如果手续费大于最大的配置那么取这个手续费
        if($data['money'] >=$fee_config[count($fee_config)-1]['max_price']){
            $fee = $fee_config[count($fee_config)-1]['fee'];
            $feel_type = $fee_config[count($fee_config)-1]['fee_type'];
        }
        else{
            foreach($fee_config as $k=>$v){
                if($data['money'] >= $v['min_price'] &&$data['money'] <= $v['max_price']){
                    $fee =  floatval($v['fee']);
                    $feel_type = $v['fee_type'];
                }
            }
        }

        if($feel_type == 1){
            $fee = $data['money'] * $fee * 0.01;
        }

        //判断提现金额限制
        if(($data['money'] + $fee + floatval($GLOBALS['user_info']['nmc_amount'])) > floatval($GLOBALS['authorized_info']['money'])){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['CARRY_MONEY_NOT_ENOUGHT'];
            return $status;
        }
        $data['fee'] = $fee;



        if($bid == 0)
        {
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PLASE_ENTER_CARRY_BANK'];
            return $status;
        }

        $user_bank = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."user_bank where user_id=".intval($GLOBALS['authorized_info']['id'])." AND id=$bid ");

        $data['bank_id'] = $user_bank['bank_id'];
        $data['real_name'] = $user_bank['real_name'];
        $data['region_lv1'] = intval($user_bank['region_lv1']);
        $data['region_lv2'] = intval($user_bank['region_lv2']);
        $data['region_lv3'] = intval($user_bank['region_lv3']);
        $data['region_lv4'] = intval($user_bank['region_lv4']);
        $data['bankzone'] = trim($user_bank['bankzone']);
        $data['bankcard'] = trim($user_bank['bankcard']);


        $data['create_time'] = TIME_UTC;
        $GLOBALS['db']->autoExecute(DB_PREFIX."user_carry",$data,"INSERT");

        //更新会员账户信息
        require APP_ROOT_PATH.'system/libs/user.php';
        modify_account(array('money'=>-$data['money'],'lock_money'=>$data['money']),$data['user_id'],"提现申请",8);
        modify_account(array('money'=>-$fee,'lock_money'=>$fee),$data['user_id'],"提现手续费",9);

        //$content = "您于".to_date($data['create_time'],"Y年m月d日 H:i:s")."提交的".format_price($data['money'])."提现申请我们正在处理，如您填写的账户信息正确无误，您的资金将会于3个工作日内到达您的银行账户.";

        $notice['time']=to_date($data['create_time'],"Y年m月d日 H:i:s");
        $notice['money']=format_price($data['money']);

        $tmpl_content = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_WITHDRAWS_CASH'",false);
        $GLOBALS['tmpl']->assign("notice",$notice);
        $content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content['content']);

        send_user_msg("",$content,0,$data['user_id'],TIME_UTC,0,true,5);

        $status['status'] = 1;
        $status['show_err'] = $GLOBALS['lang']['CARRY_SUBMIT_SUCCESS'];
    }else{
        $status['show_err'] ="未登录";
    }
    return $status;
}

function getUcRepayPlan($user_id,$status,$limit,$condition=""){
    $result = array("rs_count"=>0,"list"=>array());
    $extWhere =" 1=1 ";
    if($user_id > 0){
        $extWhere .=" and ((dlr.user_id = $user_id and dlr.t_user_id=0) or dlr.t_user_id=$user_id) ";
    }

    switch($status){
        case "1": //待还款
            $extWhere .=" and dlr.has_repay=0 ";
            break;
        case "2": //已还款
            $extWhere .=" and dlr.has_repay=1 ";
            break;
        case "3": //近期待还款
            $extWhere .=" and dlr.has_repay=0 and dlr.repay_time <=".next_replay_month(TIME_UTC,1)." ";
            break;
        case "5": //逾期还款
            $extWhere .=" and ((dlr.has_repay=1 and dlr.true_repay_time >dlr.repay_time+24*3600) OR (dlr.has_repay=0  and dlr.repay_time+24*3600 < ".TIME_UTC.")) ";
            break;
    }

    $sql_count = "SELECT count(*) FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d On d.id = dlr.deal_id where $extWhere $condition ";

    $result['rs_count'] = $GLOBALS['db']->getOne($sql_count);
    if($result['rs_count'] > 0){
        $sql_list = "SELECT dlr.*,dlr.l_key +1 as l_key_index ,d.name FROM ".DB_PREFIX."deal_load_repay dlr LEFT JOIN ".DB_PREFIX."deal d On d.id = dlr.deal_id where $extWhere $condition ORDER BY dlr.repay_time DESC LIMIT ".$limit;

        $result['list'] = $GLOBALS['db']->getAll($sql_list);
        foreach($result['list'] as $k=>$v){
            $result['list'][$k]['l_key_index'] = "第 ".$v['l_key_index']." 期";
            //状态
            if($v['has_repay'] == 0){
                $result['list'][$k]['status_format'] = '待还';
            }elseif($v['status'] == 0){
                $result['list'][$k]['status_format'] = '提前还款';
            }elseif($v['status'] == 1){
                $result['list'][$k]['status_format'] = '准时还款';
            }elseif($v['status'] == 2){
                $result['list'][$k]['status_format'] = '逾期还款';
            }elseif($v['status'] == 3){
                $result['list'][$k]['status_format'] = '严重逾期';
            }
            $result['list'][$k]['interest_money_format'] = format_price($v['interest_money'] + $v['reward_money'] - $v['manage_money'] - $v['manage_interest_money']);
            $result['list'][$k]['shiji_money'] = format_price($v['true_interest_money'] + $v['impose_money'] + $v['true_reward_money'] - $v['true_manage_money'] - $v['true_manage_interest_money']);
            $result['list'][$k]['repay_money_format'] = format_price($v['repay_money']);
            $result['list'][$k]['manage_interest_money_format'] = format_price($v['manage_interest_money']);
        }
    }
    return $result;
}







function getUcDealRepay($user_id,$limit,$condition=""){

    $result = array("rs_count"=>0,"list"=>array());
    $extWhere =" 1=1 ";
    $extWhere .=" and   has_repay=0 and user_id = ".$user_id ." and repay_time <=".next_replay_month(TIME_UTC,1)." ";

    $sql_count = "SELECT count(*) FROM ".DB_PREFIX."deal_repay where  $extWhere $condition  order by deal_id";
    $result['rs_count'] = $GLOBALS['db']->getOne($sql_count);
    if($result['rs_count'] > 0){
        $result['list']=$GLOBALS['db']->getAll("select *,l_key+1 as l_key_index from ".DB_PREFIX."deal_repay where  $extWhere $condition order by deal_id limit ".$limit);
        foreach($result['list'] as $k=>$v){
            $result['list'][$k]['name']= $GLOBALS['db']->getOne("select name from ".DB_PREFIX."deal where id = ".$result['list'][$k]['deal_id']);//贷款名称
            $result['list'][$k]['l_key_index'] = "第 ".$v['l_key_index']." 期";
            if($v['has_repay'] == 0){
                $result['list'][$k]['status_format'] = '待还';
            }elseif($v['status'] == 0){
                $result['list'][$k]['status_format'] = '提前还款';
            }elseif($v['status'] == 1){
                $result['list'][$k]['status_format'] = '准时还款';
            }elseif($v['status'] == 2){
                $result['list'][$k]['status_format'] = '逾期还款';
            }elseif($v['status'] == 3){
                $result['list'][$k]['status_format'] = '严重逾期';
            }
            $result['list'][$k]['repay_money_format'] = format_price($v['repay_money']);
            $result['list'][$k]['self_money_format'] = format_price($v['self_money']);
            $result['list'][$k]['interest_money_format'] = format_price($v['interest_money']);
        }
    }
    return $result;
}


//VIP购买 ;
function getUcSaveVipBuy($amount,$paypassword,$vip_id){
    $status = array('status'=>0,'show_err'=>'');

    if($GLOBALS['user_info']['id'] > 0){
        $paypassword = strim($paypassword);
        $amount = floatval($amount);
        $vip_id = intval($vip_id);

        if($paypassword==""){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_EMPTY'];
            return $status;
        }

        if(md5($paypassword)!=$GLOBALS['user_info']['paypassword']){
            $status['status'] = 0;
            $status['show_err'] = $GLOBALS['lang']['PAYPASSWORD_ERROR'];
            return $status;
        }



        $now_vip_grade = $GLOBALS['db']->getRow("select v.*,vt.vip_grade from ".DB_PREFIX."vip_setting v LEFT JOIN ".DB_PREFIX."vip_type vt ON v.vip_id=vt.id  where vt.id = '$vip_id'  ");

        if(!$now_vip_grade){
            $status['status'] = 0;
            $status['show_err'] = "购买的等级不存在";
            return $status;
        }
        if($vip_id == $GLOBALS['user_info']['vip_id']){
            $status['status'] = 0;
            $status['show_err'] = "您已经是".$now_vip_grade['vip_grade'];
            return $status;
        }

        $data['user_id'] = intval($GLOBALS['user_info']['id']);
        $data['money'] = $amount * $now_vip_grade['site_pirce'];
        $buy_fee = $data['money'] ;

        if($data['money'] <=0)
        {
            $status['status'] = 0;
            $status['show_err'] = "购买金额不对";
            return $status;
        }

        if((floatval($data['money'])) <= $GLOBALS['user_info']['money']){

            $user_info = get_user_info("*","id='".$data['user_id']."' and vip_id = '".$vip_id."' ");

            $vip_buy_data['user_id'] =  $data['user_id'];
            $vip_buy_data['vip_id'] =  $vip_id;
            $vip_buy_data['vip_buytime'] = TIME_UTC;
            $vip_buy_data['buy_limit'] =  $amount;
            $vip_buy_data['buy_fee'] =  $buy_fee;
            if(TIME_UTC < $user_info['vip_end_time']){
                $vip_end_time = $user_info['vip_end_time'] + $amount * 365 * 24 * 3600 ;
            }else{
                $vip_end_time = TIME_UTC + $amount * 365 * 24 * 3600 ;
            }

            $vip_buy_data['vip_end_time'] =  $vip_end_time;

            $GLOBALS['db']->autoExecute(DB_PREFIX."vip_buy_log",$vip_buy_data,"INSERT");

            $userdata['vip_end_time'] = $vip_end_time;
            $GLOBALS['db']->autoExecute(DB_PREFIX."user",$userdata,"UPDATE","id=".$data['user_id']);

            //VIP 购买升级
            $type = 1;
            $type_info = 8;
            $resultdate = syn_user_vip($data['user_id'],$type,$type_info,$vip_id);

            require_once APP_ROOT_PATH.'system/libs/user.php';
            modify_account(array('money'=>"-".$buy_fee),$data['user_id'],"VIP购买",27);

            $status['status'] = 1;
            $status['show_err'] = "用户购买VIP成功";
            return $status;

        }
        else{
            $status['status'] = 0;
            $status['show_err'] = "用户购买VIP失败";
            return $status;
        }

    }else{
        $status['show_err'] ="未登录";
    }
    return $status;
}

function replacemoney($moeny){
    return round($moeny/10000,2);
}